繁体   English   中英

Project Euler Problem 87 Code 给出错误答案

[英]Project Euler Problem 87 Code gives wrong answer

我正在做 Project Euler 的第 87 题,内容如下:

可表示为素数平方、素数立方体和素数四次方之和的最小数是 28。 事实上,在 50 以下正好有四个数可以用这种方式表示:

28 = 2 2 + 2 3 + 2 4

33 = 3 2 + 2 3 + 2 4

49 = 5 2 + 2 3 + 2 4

47 = 2 2 + 3 3 + 2 4

有多少个五千万以下的数可以表示为质数平方、质数立方和质数四次方之和?

我使用了以下代码:

public class primes {
    public static List<Integer> primeNumbersTill(int n) {
        List<Integer> primeNumbers = new LinkedList<>();
        if (n >= 2) {
            primeNumbers.add(2);
        }
        for (int i = 3; i <= Math.sqrt(n); i += 2) {
            if (isPrime(i)) {
                primeNumbers.add(i);
            }
        }
        return primeNumbers;
    }
    private static boolean isPrime(int number) {
        for (int i = 2; i*i < number; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args){
        int n = 50000000;
        List<Integer> ListofPrimes = primeNumbersTill(n);
        List<Integer> Squares = new LinkedList<Integer>();
        List<Integer> Cubes = new LinkedList<Integer>();
        List<Integer> Fourth = new LinkedList<Integer>();
        Set<Integer> Results = new HashSet<Integer>();
        
        for(int i = 0; i < ListofPrimes.size(); i++) {
            if(Math.pow(ListofPrimes.get(i),2) < n) {
                Squares.add((int) Math.pow(ListofPrimes.get(i),2));
            }
            if(Math.pow(ListofPrimes.get(i),3) < n) {
                Cubes.add((int) Math.pow(ListofPrimes.get(i),3));
            }
            if(Math.pow(ListofPrimes.get(i),4) < n) {
                Fourth.add((int) Math.pow(ListofPrimes.get(i),4));
            }
        }
            for(int j2 : Squares) {
                for(int j3 : Cubes) {
                    for(int j4 : Fourth) {
                        int sum = j2 + j3 + j4;
                        if(sum < n) {
                            Results.add(sum);
                        }
                    }
                
            }
        }
        System.out.println(Results.size());

    }
}

我得到的答案是 1 391 732,这是错误的。 有谁知道我做错了什么?

for (int i = 2; i*i < number; i++) {应该是: for (int i = 2; i*i <= number; i++) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM