c - 如何将整数表示为其质因数的乘积?

标签 c for-loop integer primes prime-factoring

//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/

相关文章:

ruby - Gets.chomp 输入比较返回错误

php - 如何验证整数值以避免 SQL 注入(inject)?

c - C 应用程序的实时图形

c++ - Printf %X 标识符 - 指针的奇怪行为

c - 使用指针交换两个整数

for-loop - 是否不鼓励在 Go 中使用单行 for 循环或 if 语句?

c - 不使用指针反转字符串

php - 循环更改时间增量,不能被 60 整除时结转到下一个小时

c# - Parallel.For 与 for

ios - 将 NSDate 转换为整数