C language brush questions notes - factor decomposition

insert image description here

Article directory

topic

Factor a positive integer into prime factors.

For example : input 90, print out 90=2*3*3*5.

insert image description here

ideas

To decompose the prime factors of n, you should first find a minimum prime number k, and then complete the following steps:

(1) If the prime number is exactly equal to n, it means that the process of decomposing the prime factors has ended, and you can print it out.

(2) If n≠k, but n is divisible by k, the value of k should be printed out, and the quotient of n divided by k, as a new positive integer you n, repeat the first step.

(3) If n is not divisible by k, use k+1 as the value of k, and repeat the first step.

answer


#include <stdio.h>


int main()
{
    
    
    int n,i;

    printf("\n请输入一个数字:\n");

    scanf("%d",&n);

    printf("%d=",n);

    for(i=2;i<=n;i++)
    {
    
    
        while(n!=i)
        {
    
    
            if(n%i==0)
            {
    
    
                printf("%d*",i);
                n=n/i;
            }
             else
             {
    
    
                 break;
             }

        }
    }

    printf("%d",n);
}


Sample output

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/124092067
Recommended