factors of a input number

Factor of number are integers when divided with the number leaves no reminder or 0 as reminder.

Example :

1,3 & 5 are three factors of number 15.
1,2,3,4,6 are factors of number 12
#include <stdio.h>
int main(void){
int i;
int num;
printf("Enter the number ");
scanf("%d",&num);

for ( i=1;i<num;i++){
if(num % i ==0){
 printf("%d,",i);
}
}
return 0;
}
Output is here if you enter 12 as input
1,2,3,4,6,
There are some numbers for which only factors are 1 and itself ( same number ) , they are known as prime numbers.

Handling Edge Cases: Zero and Negative Numbers

Zero is a special case where all integers can be considered as factors, while negative numbers typically don't have proper factors. Here's how to handle these scenarios:

#include <stdio.h>
int main(void){
    int num, i;
    printf("Enter a number: ");
    scanf("%d", &num);
    if (num == 0) {
        printf("All integers are factors of 0.\n");
    } else if (num < 0) {
        printf("Negative numbers don't have proper factors.\n");
    } else {
        printf("Factors of %d: ", num);
        for (i = 1; i <= num; i++) {
            if (num % i == 0) {
                printf("%d, ", i);
            }
        }
    }
    return 0;
}
Output:
Enter a number: -5
Negative numbers don't have proper factors.

Identifying Prime Numbers

Prime numbers have exactly two factors: 1 and the number itself. Here's how to identify if a number is prime:

#include <stdio.h>
int main(void){
    int num, i, isPrime = 1;
    printf("Enter a number: ");
    scanf("%d", &num);
    if (num < 2) {
        printf("%d is not a prime number.\n", num);
    } else {
        for (i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
        }
        if (isPrime) {
            printf("%d is a prime number.\n", num);
        } else {
            printf("%d is not a prime number.\n", num);
        }
    }
    return 0;
}
Output:
Enter a number: 7
7 is a prime number.

Using Functions to Get Factors

Using a function to find factors improves code readability and structure. Here's an example:

#include <stdio.h>
void print_factors(int num) {
    printf("Factors of %d: ", num);
    for (int i = 1; i <= num; i++) {
        if (num % i == 0) {
            printf("%d, ", i);
        }
    }
    printf("\n");
}
int main(void){
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    print_factors(num);
    return 0;
}
Output:
Enter a number: 12
Factors of 12: 1, 2, 3, 4, 6, 12, 

List of Prime Numbers Common Factors of Two input numbers


plus2net.com






We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer