Check whether a number is a perfect number.
Divisors, accumulators, and loop limits.
A perfect number is a number whose sum of proper divisors equals the number itself. For example, 6 has divisors 1, 2, and 3, and 1 + 2 + 3 = 6. To check this, we loop from 1 to n/2, and whenever a number divides n evenly, we add it to a sum. After the loop, if the sum equals n, the number is perfect; otherwise, it is not.
#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 1; i <= n / 2; i++) {
if (n % i == 0) {
sum += i;
}
}
if (sum == n) {
printf("Perfect number\n");
} else {
printf("Not a perfect number\n");
}
return 0;
}
Input: 6
Output: Perfect number
Check whether a number is prime.
Divisors, counters, and efficient loop limits.
A prime number is greater than 1 and has no divisors other than 1 and itself. We check divisibility from 2 to sqrt(n). If n is divisible by any value in that range, it is not prime. Otherwise, it is prime. This is efficient because we do not check beyond the square root.
#include <stdio.h>
#include <math.h>
int main() {
int n, i;
int isPrime = 1;
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
isPrime = 0;
} else {
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
isPrime = 0;
break;
}
}
}
if (isPrime) {
printf("Prime number\n");
} else {
printf("Not a prime number\n");
}
return 0;
}
Input: 13
Output: Prime number