//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
printf("%d ", i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
}
}
我知道这是使用for循环查找数字素因数的方法。但我不知道如何将输出整数表示为其质因数的乘积。 例如,输入是:10 || 输出为:2 x 5 = 10。我们如何做到这一点? TIA。
最佳答案
你应该:
- 保存原始值。
- 打印每个质因数之间的运算符
x
。 - 在最后打印原始值。
#include <stdio.h>
int main(void) {
int num;
int i;
int start_num;
int is_first = 1;
if(scanf("%d", &num) != 1) return 1;
start_num = num; //Save the original value.
//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
if(!is_first) printf("x "); //Print the operator before second and later operands.
printf("%d ", i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
is_first = 0; //Mark that there is already one or more operand.
}
}
printf("= %d\n", start_num); //Print the original value.
return 0;
}
关于c - 如何将整数表示为其质因数的乘积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66368449/