Project Euler 233

本文关键字:Euler Project | 更新日期: 2023-09-27 18:20:20

设f(N)为上具有整数坐标的点的数量穿过(0,0)、(N,0)、(0,N)和(N,N)的圆。

可以看出f(10000)=36.

所有正整数的和是多少1011,使得f(N)=420?

好的,我想我已经有了投影欧拉数233的基本概念。这是我的代码:

/*
 * Andrew Koroluk
 */
public class euler233 {
public static void main(String[] args) {
    System.out.println(f(10000));
    System.out.println(f(1328125));
    System.out.println(f(84246500));
    System.out.println(f(248431625));
    //if(true) return;
    double ans = 0;
    for(double N=10000; N<=(Math.pow(10, 11)); N++) {
        //System.out.println(N);
        if( f(N)==420 ) {
            ans+= N;
            System.out.println(N);
        }
    }
    System.out.println(ans);
}
static double f(double N) {
    double ans = 0;     
    double r = Math.sqrt(2*N*N)/2;
    //System.out.println(r*r);
    double r2 = r*r;
    for(int x=1; x<=r; x++) {
        for(int y=1; y<=r; y++) {
            if( x*x + y*y == r2 ) {
                ans+=4;
                break;
            }
        }
    }
    return ans;
}
static boolean isInt(double a) {
    if(a==(int)a) return true;
    return false;
}
}

基本上,我正在做的是找到圆内直角三角形的解,三角形的斜边长度等于圆的直径。我不确定我的代码是否正确。

如果它是正确的,那么我的问题是优化f(N)函数,并优化循环以找到f(N)=420的数字。

新代码:

public class euler233 {
    static long[] primes;
    public static void main(String[] args) {
        System.out.println(r(1328125));
        Clock c = new Clock();
        System.out.println(f2(10000));
        c.getTimeSeconds();
        c.reset();
        System.out.println(f2(1328125));
        c.getTimeSeconds();
    }
    static long f2(long N) {
        return SquaresR2(N*N);
    }
    static boolean isInt(long a) {
        if(a==(int)a) return true;
        return false;
    }
    static int SquaresR2(long n) {
        //System.out.println("start");
        int sum = 0;
        outer:
        for(int a=0; a<Math.sqrt(n)-1; a++) {
            for(int b=0; b<Math.sqrt(n)-1; b++) {
                if( a*a + b*b == n ) {
                    if(a>b) break outer;
                    sum+=4;
                    System.out.println(n+" = "+a+"^2 + "+b+"^2");
                }
            }
        }
        sum*=2;
        if(Math.sqrt(n)==(int)Math.sqrt(n)) sum+=4;
        return sum;
    }
    static int r(int n) {
        return 4*(d1(n) - d3(n));
    }
    private static int d1(int n) {
        int k=1, sum=0;
        while(true) {
            int d = 4*k+1;
            if(d>n) break;
            if(n%d==0) sum++;
            k++;
        }
        return sum;
    }
    private static int d3(int n) {
        int k=1, sum=0;
        while(true) {
            int d = 4*k+3;
            if(d>n) break;
            if(n%d==0) sum++;
            k++;
        }
        return sum;
    }
}

Project Euler 233

几点:

  1. 不要使用浮点数
  2. 除此之外,您的算法原则上是正确的
  3. 但它不会在宇宙热死之前结束

你必须找到一个更好的方法,一些提示:

  1. 只使用整数数学
  2. 看看数论导论。正方形和直角三角形可能很有趣。哦,还有素数
  3. 玩得开心
  4. 让我重复一遍,数论(但非常基础,你可以理解高中数学背景的相关部分;不过你需要投入一些时间)