Problem: Write a c program to find and display all factors of a number excluding 1 and the number itself.
Example:
Input: 30 Output: 2, 3, 5, 6, 10, 15 Input: 7 Output: Prime Number
To display all factors of a given number in C, you would need to follow the following steps:
- Input a number from the user.
- Loop from 2 to num/2
- Check if the loop variable divides the input number. If so, then output it.
- If none of the loop variable divides the number, then the input is a prime number.
Here is the implementation of the above steps in C:
#include <stdio.h>
int main() {
int num, i, factors = 0;
// Read input number from user
printf("Enter a positive integer: ");
scanf("%d", &num);
// Check if the number has any factors
printf("Factors of %d (excluding 1 and itself): ", num);
for (i = 2; i <= num/2; i++) {
if (num % i == 0) {
printf("%d ", i);
factors++;
}
}
// If the number has no factors, it is prime
if (factors == 0) {
printf("%d is a prime number.\n", num);
} else {
printf("\n");
}
return 0;
}
Output:
Enter a positive integer: 30
Factors of 30 (excluding 1 and itself): 2 3 5 6 10 15
In the above program, we first ask the user to input a positive number, then we loop from 2
to num/2
to check for the factors.
Inside the loop, we check if the current loop variable (ie. i
) divides num
or not. If yes, we output it and update the factors counter variable.
This outputs all the possible factors of the input number.
If the number doesn’t have any factors excluding 1 and itself, then the value of the factors counter variable i.e. factors
will remain zero.
Therefore, for this case, we check outside the end of the loop that if factors is 0. If so, then the input number is prime and we output the same.