Programs to check if a number is a perfect number or not have been shown here. A perfect number is a positive integer that is equal to the sum of its proper divisors. For example 6 is a perfect number because if we add it's proper divisors (1, 2 and 3), we get 6 i.e. 1 + 2+ 3 = 6. Some of the other perfect numbers are 28, 496, 8128 etc.
1. Program to Check If a Number is a Perfect Number or Not
1.1. C Program to Check If a Number is a Perfect Number or Not
Code has been copied
/************************** alphabetacoder.com C program to check if a number is a perfect number ***************************/ #include <stdio.h> int main() { // declare variables int n, i, sum = 0; // take input printf("Enter the number: "); scanf("%d", & n); // add all the divisor upto n / 2 for (i = 1; i <= (n / 2); i++) { if (n % i == 0) sum = sum + i; } // check if the input number // is equal to the sum if (n == sum) printf("%d is a perfect number", n); else printf("%d is not a perfect number", n); return 0; }
Output
Case 1:
Enter the number: 6
6 is a perfect number
Case 2:
Enter the number: 10
10 is not a perfect number
Case 3:
Enter the number: 28
6 is a perfect number
No comments:
Post a Comment
If you have any doubts or suggestions, please leave a note.