Prime Factorization in C: Step-by-Step Code
In order to solve the problem of factoring numbers, you can write a program to implement this function. Here is a simple program example using the C language to factor numbers.
#include <stdio.h>
void primeFactors(int n) {
// 打印出所有的2因子
while (n % 2 == 0) {
printf("%d ", 2);
n = n / 2;
}
// n现在必须是一个奇数
for (int i = 3; i * i <= n; i = i + 2) {
while (n % i == 0) {
printf("%d ", i);
n = n / i;
}
}
// 如果n本身是一个质数大于2
if (n > 2) {
printf("%d ", n);
}
}
int main() {
int n;
printf("请输入一个数字:");
scanf("%d", &n);
printf("分解质因数为:");
primeFactors(n);
return 0;
}
The program first defines a function called primeFactors, which calculates and prints the prime factors of a given number. Then in the main function, the user inputs a number and the primeFactors function is called to decompose and print out the prime factors.
After running the program, input a number, and the program will output all the prime factors of that number.