patterncsharpMinor
smallest number divisible by all numbers from 1 to 20? Project Euler question 5
Viewed 0 times
smallestnumberallnumbersdivisibleprojecteulerfromquestion
Problem
I'm currently working my way through the questions on Project Euler and I am on question 5. Is this the best possible solution? Any suggestions welcomed!
List divisors = new List{ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int n = 1;
while (true)
{
n++;
foreach (int d in divisors)
{
if (n % d != 0) { break; }
if (d==20)
{
Console.Write(n);
Console.ReadLine();
}
}
}Solution
The most optimal solution would be to calculate the LCM of 1 to 20 directly using the standard Euclidean algorithm.
In terms of complexity, this algorithm is roughly
// calculate GCD using Euclidean algorithm
public long GCD(long a, long b) {
if (b == 0)
return a;
else
return GCD(b, a % b);
}
// calculate LCM using simple formula based on GCD
public long LCM(long a, long b) {
var gcd = GCD(a, b);
return a * b / gcd;
}
// iteratively calculate LCM of 1 through 20
public static void Main(string args[]) {
long result = 1;
// loop through each value 1 to 20, and LCM with previous result
for (long n = 2; n <= 20; n++) {
result = LCM(result, n);
}
// print out the result
Console.WriteLine(result);
}In terms of complexity, this algorithm is roughly
O(n) for small n.Code Snippets
// calculate GCD using Euclidean algorithm
public long GCD(long a, long b) {
if (b == 0)
return a;
else
return GCD(b, a % b);
}
// calculate LCM using simple formula based on GCD
public long LCM(long a, long b) {
var gcd = GCD(a, b);
return a * b / gcd;
}
// iteratively calculate LCM of 1 through 20
public static void Main(string args[]) {
long result = 1;
// loop through each value 1 to 20, and LCM with previous result
for (long n = 2; n <= 20; n++) {
result = LCM(result, n);
}
// print out the result
Console.WriteLine(result);
}Context
StackExchange Code Review Q#25200, answer score: 6
Revisions (0)
No revisions yet.