能够高效打印给定数字的所有质因子的 C 语言程序?
本节中,我们将了解如何高效地获取某个数字的所有素因数。例如数字 n = 1092,我们需要获取其所有素因数。1092 的素因数为 2、2、3、7、13。要解决这个问题,我们必须遵循以下规则:
如果这个数字能被 2 整除,则打印 2,并将这个数字反复除以 2。
现在这个数字肯定为奇数。现在从 3 到这个数字的平方根,如果数字能被当前的值整除,则打印,然后用当前数字除以这个数字来改变这个数字,然后继续。
让我们看一看算法以获得更好的思路。
算法
printPrimeFactors(n)
begin while n is divisible by 2, do print 2 n := n / 2 done for i := 3 to √𝑛, increase i by 2, do while n is divisible by i, do print i n := n / i done done if n > 2, then print n end if end
示例
#include<stdio.h> #include<math.h> void primeFactors(int n) { int i; while(n % 2 == 0) { printf("%d, ", 2); n = n/2; //reduce n by dividing this by 2 } for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers while(n % i == 0) { printf("%d, ", i); n = n/i; } } if(n > 2) { printf("%d, ", n); } } main() { int n; printf("Enter a number: "); scanf("%d", &n); primeFactors(n); }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Enter a number: 24024 2, 2, 2, 3, 7, 11, 13,
广告