Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program to check Plus Perfect Number
A Plus Perfect Number (also known as Armstrong Number or Narcissistic Number) is a number where the sum of its digits raised to the power of the number of digits equals the original number itself.
Syntax
int isPlusPerfect(int number);
For example −
- 371: 3³ + 7³ + 1³ = 27 + 343 + 1 = 371 ?
- 163: 1³ + 6³ + 3³ = 1 + 216 + 27 = 244 ? 163 ?
Example 1: Checking Multiple Numbers
#include <stdio.h>
int power(int base, int exp) {
int result = 1;
while (exp > 0) {
result *= base;
exp--;
}
return result;
}
int countDigits(int n) {
int count = 0;
while (n != 0) {
count++;
n /= 10;
}
return count;
}
int isPlusPerfect(int n) {
int original = n;
int digits = countDigits(n);
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += power(digit, digits);
n /= 10;
}
return (sum == original);
}
int main() {
int numbers[] = {371, 163, 1634, 9474};
int size = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < size; i++) {
if (isPlusPerfect(numbers[i])) {
printf("%d is a Plus Perfect Number<br>", numbers[i]);
} else {
printf("%d is not a Plus Perfect Number<br>", numbers[i]);
}
}
return 0;
}
371 is a Plus Perfect Number 163 is not a Plus Perfect Number 1634 is a Plus Perfect Number 9474 is a Plus Perfect Number
Example 2: Finding Plus Perfect Numbers in a Range
#include <stdio.h>
int power(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
}
return result;
}
int countDigits(int n) {
int count = 0;
while (n != 0) {
count++;
n /= 10;
}
return count;
}
int isPlusPerfect(int n) {
int original = n;
int digits = countDigits(n);
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += power(digit, digits);
n /= 10;
}
return (sum == original);
}
int main() {
int start = 1, end = 1000;
printf("Plus Perfect Numbers between %d and %d:<br>", start, end);
for (int i = start; i <= end; i++) {
if (isPlusPerfect(i)) {
printf("%d ", i);
}
}
printf("<br>");
return 0;
}
Plus Perfect Numbers between 1 and 1000: 1 2 3 4 5 6 7 8 9 153 371 407
Key Points
- Single digit numbers (1-9) are always Plus Perfect Numbers since d¹ = d
- Three-digit examples: 153, 371, 407
- Four-digit examples: 1634, 8208, 9474
- The algorithm has O(d) time complexity where d is the number of digits
Conclusion
Plus Perfect Numbers are special numbers where each digit raised to the power of total digits equals the original number. They are useful for understanding digit manipulation and mathematical operations in C programming.
Advertisements
