C ++和Project Euler#3编译错误

时间:2013-04-20 18:00:59

标签: c++ compiler-errors

#import <cmath>
#import <iostream>
using namespace std;

int main {
    int a;
    for(int x = 600851475142; x>cmath::sqrt(600851475143); x--) {
        if (600851475143%x==0) { //is it a factor of 600851475143?
            if p(x) { //is it also a prime?
                cout << x;
                return 0;
            }
        }
    }
}

bool p(int n) {
    for(int x = n; x<cmath::sqrt(n)+1; x++) {
        if (n%x==0) {
            return false;
        }
    }
    return true;
}

这是项目euler#3(http://projecteuler.net/problem=3)的代码。我对C ++比较陌生。

基本上我的方法是从600851475143倒数,测试数字是否为600851475143,然后看它是否是素数。如果是,那么返回数字并退出。 但是,当我编译我的代码时,我收到错误:

error: function definition does not declare parameters
In function 'bool p(int)':
error: 'cmath' has not been declared

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

看看你的代码,你似乎至少对C ++不熟悉,如果不是编程本身。

1)在C ++中,我们使用#include而不是#import

2)你需要在调用之前声明一个函数。 类似的东西:

bool p(int n);
主要功能之前

3)主要功能中缺少括号。应该是:'int main(){'

4)你不需要cmath :: for sqrt。写一些像:     (int)sqrt((double)600851475143) 这是因为sqrt不在参数

中取整数

5)'如果p(x){'应为'if(p(x)){'

6)函数中的for循环总是在增加。

7)在for-loop之前计算sqrt是个好主意,而不是在for循环中计算。

8)欢迎来到编程世界!

答案 1 :(得分:0)

标题的名称为cmath,但sqrt位于名称空间std

另外:您可能想要在循环之前计算平方根,然后针对该结果进行测试:

bool p(int n) { 
    int limit = std::sqrt(n)+1;
    for (int x=n; x<limit; x++)
    // ...
}