速度
只需使用所需的大小,即可提高效率。对于从 -2^31 到 2^31 的数字,整数很好。如果使用 long,其中 int 就足够了,则会减慢代码的速度。例如,此代码在我的计算机上以 7.116 秒的速度运行。通过将其切换到使用 int,我将计算机上的运行时间减少到 3.74 秒:
public class Problem005 {
private static boolean isDivisibleByAll(long n, long ceiling) {
for (long i = 1; i < ceiling; i++)
if (n % i != 0)
return false;
return true;
}
public static long findSmallestMultiple (long ceiling) {
long number = 1;
while (!isDivisibleByAll(number, ceiling))
number++;
return number;
}
}
public class Stopwatch {
private final long start;
public Stopwatch() {
start = System.currentTimeMillis();
}
public double elapsedTime() {
long now = System.currentTimeMillis();
return (now - start) / 1000.0;
}
}
public class Main {
public static void main(String[] args) {
Stopwatch stopwatch005 = new Stopwatch();
long highestMultiple = 20;
long findSmallestMultipleOutput = findSmallestMultiple(highestMultiple);
double findSmallestMultipleTime = stopwatch005.elapsedTime();
System.out.println("Problem #005");
System.out.println("============");
System.out.print("The multiple of the numbers 1-" + highestMultiple + " is = ");
System.out.print(findSmallestMultipleOutput);
System.out.println(" with a time of " + findSmallestMultipleTime + " seconds.\n ");
}
}
更改为使用 int:
public class Problem005 {
private static boolean isDivisibleByAll(int n, int ceiling) {
for (int i = 1; i < ceiling; i++)
if (n % i != 0)
return false;
return true;
}
public static int findSmallestMultiple (int ceiling) {
int number = 1;
while (!isDivisibleByAll(number, ceiling))
number++;
return number;
}
}