How to factorize in C language?

Decomposing a number into its prime factors is the process of breaking down a positive integer into the product of prime numbers. Below is an example code in C language that implements decomposing a number into its prime factors.

#include <stdio.h>

void primeFactorization(int n) {
    int i;
    for (i = 2; i <= n; i++) {
        if (n % i == 0) {
            printf("%d ", i);
            n /= i;
            i--;
        }
    }
}

int main() {
    int n;
    printf("请输入一个正整数:");
    scanf("%d", &n);
    printf("质因数分解结果为:");
    primeFactorization(n);
    return 0;
}

When running this code, the program will ask for a positive integer as input and then output the prime factorization of that number.

For example, if the input number is “30”, the program will output “The prime factorization result is: 2 3 5”, indicating that 30 can be factorized into the product of 2, 3, and 5.

bannerAds