我正在试图找到一种方法,以便更快地以更优化的方式解决这个特定问题。我不知道是否有可能让这些代码在多个内核和线程上运行,或者如果我能以某种方式将其卸载到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");
}
}
答案 0 :(得分:1)
最大的负担是循环,所以如果我们想获得优化的东西,最好解决。 你必须扭转问题,而不是寻找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次操作。根据“分而治”的原则。 :)