我正在尝试找出一种方法,以便更快、更优化地解决这个特定问题。我不知道是否可以让此代码在多个核心和线程上运行,或者是否可以以某种方式将其卸载到 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”是否有一些优化,但通常执行一个 Action (2 ^ 15) ^ 2 比执行 2 ^ 30 更好,它给出了 15 次操作,它给出了 29 次操作。根据“分而治之”的原则。 :)
关于java - 有没有更优化的方法在java中进行简单计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35665240/