我试图解决Project Euler的问题5,但程序崩溃并且我没有收到任何错误:
#include <stdio.h>
#include <iostream>
using namespace std;
/* Problem 5:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
*/
int selle(int number) {
int c = 0;
for (int i = 0; i <= 20; i++)
if (number % i == 0)
c++;
return c;
}
int problem(int number) {
while (number > 0) {
if (selle(number) == 20)
return number;
number++;
}
return 404;
}
int main() {
long long number = 2;
cout << problem(number);
system("PAUSE");
return 0;
}
我认为问题出在第一个函数的“for”循环中,但我不知道它是什么。也试图将功能设置为很长时间才发生。 谢谢。
答案 0 :(得分:4)
for (int i = 0; i <= 20; i++)
if (number % i == 0)
c++;
当i
为零(第一次迭代)时......你除以零......这是不允许的。
这就是你的程序崩溃的原因。
答案 1 :(得分:0)
问题是你在某个时候正在执行number % 0
。像除零一样,也不允许以模0为模。如果模运算中的第二个操作数为0,则会导致未定义的行为(http://en.cppreference.com/w/cpp/language/operator_arithmetic)。
顺便说一下,您可以从long long number = 20;
开始,然后按20(number += 20;
)执行增量,因为您不会在其间找到任何匹配。