Search code examples
cfor-loopintegerprimesprime-factoring

How to express integer as a product of its prime factors?


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

I know that this is the way of finding the prime factors of a number using for loop. But I don't know how to express the output integer as a product of its prime factors. For example, INPUT IS: 10 || OUTPUT IS: 2 x 5 = 10. How do we do this? TIA.


Solution

  • You should:

    • Save the original value.
    • Print the operator x between each prime factors.
    • Print the original value at the end.
    #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;
    }