在 java 中是否有更优化的方法来进行简单计算?

Is there a more optimized way to do a simple computation in java?

我正在尝试找出一种方法,以便更快、更优化地解决这个特定问题。我不知道是否可以在多个内核和线程上使用此代码 运行,或者我是否可以以某种方式将其卸载到 GPU,但计算速度越快越好。

public class numberCounter 
{
    public static void main(String[] args) 
    {
        //Used only to check speed of calculation
        long start = System.currentTimeMillis();

        //Initialized variables
        double x, y, z;

        //30 can be substituted out but i used it as a test. 
        //I am unable to calculate 31 and above.
        long t = (long) Math.pow(2, 30);

        //used later for counting
        long counter = 0;

        //starting number
        System.out.println("Number - " + t);

        for(int i = 1; i < t; i++)
        {
            x = i % 2;
            y = i % 3;
            z = i % 5;

            if(x*y*z > 0)
                counter++;
        }

        System.out.println();

        //prints out number of numbers that follow the rule above
        System.out.printf("Numbers: %.0f\n", counter);

        long end = System.currentTimeMillis();

        //prints out time taken
        System.out.println((end - start) + " ms");

    }
}

最大的负担是循环,所以如果想在优化上有所收获,最好解决。 你必须扭转这个问题,而不是寻找不可被 2 或 3 或 5 整除的数字,我们正在寻找可被 2 或 3 或 5 整除的数字。这些数字的结果减去所有数字将得到不可分割的数字数字乘以 2 或 3 或 5。这样,我们得到一个执行时间恒定的算法。执行时间不依赖于输入。

public static long indivisbleBy_2or3or5(long t) {
    long x, y, z;

    //amount of numbers divisible by 2, and several for 3 and 5. 
    x = t / 2;

    //amount of numbers divisible by 3 - numbers divisible by 3 and 2 = amount of numbers divisible by 3, and several for 5.
    y = t / 3;
    y = y - y / 2;

    //amount of numbers divisible by 5 - numbers divisible by 5 and 2 - (numbers divisible by 5 and 3 - numbers divisible by 5 and 3 and 2)  = number only divisible by 5  
    z = t / 5;
    z = z - z / 2 - (z / 3 - z / (2 * 3) );

    //All numbers - (The amount of numbers divisible by 2, and several for 3 and 5 
    //+ The amount of numbers divisible by 3 and several for 5 + number only divisible by 5)
    //= indivisible by 2 or 3 or 5
    return t - (x + y + z);
}

我不知道 "pow" 是否有一些优化,但通常执行操作 (2 ^ 15) ^ 2 给出 15 个操作比 2 ^ 30 给出 29 个操作更好.根据"divide et impera"的原则。 :)