简体   繁体   English

素数分解,更改输出。

[英]Prime factorization, changing output.

Hello guys i have this code. 大家好,我有这段代码。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned int num,i,j;
    int a=0;
    printf("Please input a number: ");
    scanf("%d",&num);
    printf("The Prime Factorization: ");
    for (i=2;i<=num;i++){
        if (num%i==0){
                a=1;
                if (i==num){
                printf(" %ld ",num);
                } else {
                    printf(" %ld *",i);
                    num/=i;
                }
        }


    }
    if (a==0){
            printf("%ld ",num);
    }


    return 0;
}

so let's say i input 40, it gives me 假设我输入40,它给了我

The Prime Factorization: 2 * 4 * 5 素数分解:2 * 4 * 5

this is correct but, how could I make it output the "2 * 4 * 5" as "2 ^ 3 * 5"? 这是正确的,但是我如何使其将“ 2 * 4 * 5”输出为“ 2 ^ 3 * 5”?

Since a prime can appear more than once in the factorization you can't just move on to the next candidate without first testing the current prime until the number is no longer divisble by it. 由于素数在因式分解中可以出现多次,因此您不能不先测试当前素数就继续移动到下一个候选项,直到该数不再可被其除。

And to get the nice printout you're after, you can keep a count variable as shown below: 为了获得理想的打印输出,可以保留一个count变量,如下所示:

#include <stdio.h>

int main(void) {
    unsigned int num,i,count;
    int a=0;
    printf("Please input a number: ");
    scanf("%d",&num);
    printf("The Prime Factorization: ");
    i = 2;
    while(num>1){
        if (num%i==0){
                a=1;
                count = 1;
                num /= i;

                // Exhaust each prime fully:
                while (num%i==0) {
                    count++;
                    num /= i;
                }

                printf("%ld",i);
                if (count > 1) {
                    printf(" ^ %ld", count);
                }
                if (num > 1) {
                    printf(" * ");
                }
        }
        i++;
    }
    if (a==0){
            printf("%ld ",num);
    }


    return 0;
}

something like this: 像这样的东西:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int num,i,j,count=0;
    int a=0;
    printf("Please input a number: ");
    scanf("%d",&num);
    printf("The Prime Factorization: ");
    for (i=2;i<=num;i++){
        count=0;
        a=0;
        while(num%i==0){
            a=1;
            ++count;
            num/=i;
            }
        if(a==1)
       {
            printf("%d ^ %d *",i,count);
        }
   }
   if (a==0){
        printf("%ld ",num);
}
return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM