【问题标题】:Time Exceeded for a project Euler test项目欧拉测试的超时时间
【发布时间】:2013-08-04 17:40:07
【问题描述】:

我刚刚开始在 Euler 项目上解决问题(并且是 C 代码的初学者)。

问题 1 状态:如果我们列出所有小于 10 且是 3 或 5 的倍数的自然数,我们得到 3、5、6 和 9。这些倍数的和是 23。求所有的倍数之和3 或 5 低于 1000。我很确定我的代码是正确的(或者可能不是)。现在,当我在 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;
}

【问题讨论】:

    标签: c compilation timeout


    【解决方案1】:

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

    【讨论】:

    • 哦!谢谢!哈哈我的错。呃,我的代码显然仍然是错误的。 (就问题而言)
    • 解决了。再次感谢!
    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 2014-03-08
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多