项目欧拉,#3好奇心

时间:2016-07-02 19:40:36

标签: c

项目欧拉 - 3 ---问题

我是编程艺术的初学者,我开始做项目欧拉问题。

我曾尝试在C中做第3个问题,但我不明白为什么它不起作用。

    #include <stdio.h>
    #include <stdlib.h>
    int main ()
    {
            int prime = 0;
            long long number, factor, primeFactor = 0, i;
            printf("\n\nNumber :");
            scanf("%lld", &number);
            factor = number;
            while (primeFactor == 0) {
                    factor --;
                    if (number % factor == 0) {
                            for (i = 2; i < factor; i++) {
                                    if (factor % i == 0) {
                                            prime = 0;
                                    }
                            }
                            if (prime) {
                                    primeFactor = factor;
                            }
                    prime = 0;
                    }
            }
            if (primeFactor == 0) {
                    printf("\nIt has no prime factors.\n\n");
            }
            else printf("\n%lld\n", primeFactor);
            return 0;
    }

那么,有人可以向我解释为什么它不起作用吗?

谢谢! :)

1 个答案:

答案 0 :(得分:0)

你对内循环的逻辑是错误的,就像BLUEPIXY暗示的那样,你需要做相反的事情:

#include <stdio.h>
#include <stdlib.h>
int main ()
{
        int prime = 0;
        long long number, factor, primeFactor = 0, i;
        printf("\n\nNumber :");
        scanf("%lld", &number);
        factor = number;
        while (primeFactor == 0) {
                factor--;
                printf("%lld %lld\n",number,factor);
                if (number % factor == 0) {
                        for (i = 2; i < factor; i++) {
                                if (factor % i == 0) {
                                        prime = 1;
                                }
                        }
                        if (!prime) {
                                primeFactor = factor;
                        }
                prime = 0;
                }
        }
        if (primeFactor == 0) {
                printf("\nIt has no prime factors.\n\n");
        }
        else printf("\n%lld\n", primeFactor);
        return 0;
}

另外:1不是素数,你也需要检查。输入本身也没有被检查(这里必须大于1)。

请了解如何使用调试器。不,真的,知道如何将调试器用于您学习的语言与学习语言本身一样重要。