Selected C language experiment exercises for university computer basics (3) Experiment 4-6 decompose prime factors and express

Experiment 4-6 prime factorization

Write the program dispose.c, input a natural number n, and decompose n into prime factors and multiply the output form. For example, input 756, then output 756=2 2 3 3 3*7.

The format requires input: scanf("%d", &n) Output: (1) If n<=1 or n>2000, then printf("ERROR")
(2) If input 756, output 756=2 2 3 3 3*7, design output according to this format

Save, compile, run, and test successfully, compress the source file (.c or .cpp) and submit.

For a simpler question, start dividing from 2. If x is his factor, divide it all at once, see the code for details

#include<stdio.h>
#include<string.h>
#define maxn 10000+5
int main()
{
    
    
    int n,i=2,k=0;
    int p[maxn];
    int num[maxn];
    scanf("%d",&n);
    int tt=n;
    if(n<=1||n>2000)
    {
    
    
        printf("ERROR");
        return 0;
    }
    while(n>1)
    {
    
    
        if(n%i==0)
        {
    
    
            p[k]=i;
            while(n%i==0)
            {
    
    
                n/=i;
                num[k]++;
            }
            k++;
        }
        i++;
    }
    printf("%d=%d",tt,p[0]);
    num[0]--;
    for(i=0;i<k;i++)
    {
    
    
        while(num[i])
        {
    
    
            printf("*%d",p[i]);
            num[i]--;
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/STL_CC/article/details/105870661