Speed
You have efficiency gains by only using the size that you need. An int is fine for numbers from -2^31 to 2^31. If you use a long where an int would suffice, you slow down your code. For example, this code runs at 7.116 seconds on my machine. By switching it to using int, I decrease the running time to 3.74 seconds on my machine:
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 ");
}
}
Changed to use 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;
}
}