write a c program to calculate the factors of a number


C program to calculate the factors of a number by running the loop up to n.

#include <stdio.h>
 
int main() {
    int number;
 
    // Input the number from the user
    printf("Enter a positive integer: ");
    scanf("%d", &number);
 
    if (number <= 0) {
        printf("Please enter a positive integer.\n");
    } else {
        printf("Factors of %d are: ", number);
 
        // Loop from 1 to the number and check for factors
        for (int i = 1; i <= number; ++i) {
            if (number % i == 0) {
                printf("%d ", i);
            }
        }
 
        printf("\n");
    }
 
    return 0;
}
 

 C program to calculate the factors of a number by running the loop up to n/2.

#include <stdio.h>
 
int main() {
    int number;
 
    // Input the number from the user
    printf("Enter a positive integer: ");
    scanf("%d", &number);
 
    if (number <= 0) {
        printf("Please enter a positive integer.\n");
    } else {
        printf("Factors of %d are: ", number);
 
        // Loop from 1 to n/2
        for (int i = 1; i <= number / 2; ++i) {
            if (number % i == 0) {
                printf("%d ", i);
            }
        }
 
        // Print n itself as a factor
        printf("%d ", number);
        printf("\n");
    }
 
    return 0;
}
 
   

 C program to calculate the factors of a number by running the loop up to the square root of n.

#include <stdio.h>
#include <math.h>
 
int main() {
    int number;
 
    // Input the number from the user
    printf("Enter a positive integer: ");
    scanf("%d", &number);
 
    if (number <= 0) {
        printf("Please enter a positive integer.\n");
    } else {
        printf("Factors of %d are: ", number);
 
        // Loop from 1 to the square root of the number
        for (int i = 1; i <= sqrt(number); ++i) {
            if (number % i == 0) {
                printf("%d ", i);
 
                // If i is not equal to number/i, then print the other factor
                if (i != number / i) {
                    printf("%d ", number / i);
                }
            }
        }
 
        printf("\n");
    }
 
    return 0;
}
 


No comments:

Post a Comment