超过项目欧拉测试的时间

时间:2013-08-03 14:47:02

标签: c compilation timeout

我刚刚在项目Euler(和一个带C代码的初学者)上解决了问题。

问题1指出:如果我们列出10以下的所有自然数是3或5的倍数,我们得到3,5,6和9.这些倍数的总和是23.找到所有倍数的总和低于1000的3或5.我很确定我的代码是正确的(或者可能不是)。现在,当我在codepad.org或ideone.com等网站上编译我的代码时,它会说“超出时间”。我猜测代码运行时间太长了?为什么会这样?

我的解决方案:

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

int main (int argc, char *argv[]){

    int i, j = 0;
    for (i = 1; i <= 1000; i++){   //Traverses all the positive numbers under 1000
        while ( (i % 5 == 0) || (i % 3 == 0)){  
               j = j + i;          //If it's a multiple of 3 or 5 add it to the sum
           }
    }

    printf("The sum of all multiples of 3 and 5 under 1000 is: %d", j);

    return 0;
}

1 个答案:

答案 0 :(得分:4)

你的while语句应该是if语句。 while会带您进入无限循环,因为当您正在测试的条件满足时,您永远不会更改循环内i的值。