Click here to Skip to main content
13,143,774 members (32,108 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


Posted 11 Aug 2011

Project Euler Problem #5

, 11 Aug 2011
Rate this:
Please Sign up or sign in to vote.
Project Euler Problem #5

Ready or not, here comes problem five!

2520 is the smallest number that can be divided by each of the numbers 
from 1 to 10 without any remainder. 

What is the smallest positive number that is evenly divisible by all of 
the numbers from 1 to 20? 

This one really doesn't require that much explanation. I suppose we could easily brute force this one also, but that just isn't my style. So I'll just go ahead and show the final return statement that gives us the answer:

return Enumerable.Range(1, 20).Aggregate(this.LeastCommonDivisor);

....Alright....that's it. Let's go home.


Okay fine. Let me explain a bit. We are using the 'Aggregate' Extension here on our range of 1-20. The 'Aggregate' method will take our recursive method 'LeastCommonDivisor'.

Here is that function:

private int LeastCommonDivisor(int i, int j)
   return (i == 0) || (j == 0) ? 0 : (i / this.GreatestCommonDivisor(i, j)) * j;

That function also makes reference to this function to recursively find the greatest common divisor:

private int GreatestCommonDivisor(int i, int j)
   return (j == 0) ? i : this.GreatestCommonDivisor(j, i % j);

Now our 'Aggregate' method will calculate the smallest positive number that is evenly divisible by all of the numbers from 1 to 20.

This problem was not that enjoyable to me, but oh well. I found some great references by Basildon Coder and Functional Fun. From these guys, I was able to figure something out. Anyways, here it is. Do with it what you will.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jared Wallace
Business Analyst
United States United States
Visit my blog, Aimless Technical Babble

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 11 Aug 2011
Article Copyright 2011 by Jared Wallace
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid