You're asking for a program which computes the least common multiple of 1, 2, 3, ..., n. You can do this with recursion:
// Compute lcm(1, 2, 3, ..., n-1, n).
public static void smallestMultiple(long n) {
if (n < 3) return n;
return lcm(smallestMultiple(n-1), n);
}
public static long lcm(long m, long n) {
// Note: divide before multiplying to avoid overflow.
return (m / gcd(m, n)) * n;
}
// Computes the greatest common divisor by Euclid's algorithm
public static long gcd(long m, long n) {
if (m == 0) return n;
if (n == 0) return m;
return gcd(n, m%n);
}
You might consider binary splitting, which avoids large numbers until the end. For this problem it's not too important, but this approach would be much faster if your inputs were large and you were using bignums.
// Compute lcm(1, 2, 3, ..., n-1, n).
public static void smallestMultiple(long n) {
return lcmRange(2, n);
}
// Compute lcm(lower, lower+1, ..., upper-1, upper).
public static long lcmRange(long lower, long upper) {
long diff = upper - lower;
if (diff > 2) {
long mid = lower + diff/2;
return lcm(lcmRange(lower, mid), lcmRange(mid+1, upper));
}
if (diff == 2) return lcm(lower, upper);
return lower;
}
// Reduce least common multiple to greatest common divisor.
public static long lcm(long m, long n) {
// Note: divide before multiplying to avoid overflow.
return (m / gcd(m, n)) * n;
}
// Computes the greatest common divisor by Euclid's algorithm
public static long gcd(long m, long n) {
if (m == 0) return n;
if (n == 0) return m;
return gcd(n, m%n);
}
Prime factorization works even better: take the product of all primes from 2 to n, times the product of all the primes from 2 to sqrt(n), times the product of all the primes from 2 to cbrt(n), etc. This is pretty fast if done recursively as above.
Of course since your code overflows for n > 43 you could also just hardcode the first 43 values:
private static long[] smallestMult = { 1, 2, 6, 12, 60, 60, 420, 840, 2520, 2520, 27720, 27720, 360360, 360360, 360360, 720720, 12252240, 12252240, 232792560, 232792560, 232792560, 232792560, 5354228880, 5354228880, 26771144400, 26771144400, 80313433200, 80313433200, 2329089562800, 2329089562800, 72201776446800, 144403552893600, 144403552893600, 144403552893600, 144403552893600, 144403552893600, 5342931457063200, 5342931457063200, 5342931457063200, 5342931457063200, 219060189739591200, 219060189739591200, 9419588158802421600};
// Return lcm(1, 2, 3, ..., n-1, n).
public static void smallestMultiple(long n) {
return smallestMult[n-1];
}