Phil Haack’s Mini Math Challenge

29. January 2010

Today Phil Haack posted a mini math challenge on twitter…

24a3e96dbc652aa721bed99dcea38b6d

This seemed like a good opportunity to launch js.Fiddle and hack out some code…

 

The answer... is 2520 ;)

Blog


Comments

Ryan campbell
Ryan campbell
1/29/2010 4:10:41 PM #
I'm not sure you really need a program to figure this one out. I did it with my calculator in about 10 seconds. You just need to realize that a number divisible by 9 is also divisible by 3. Same for eight and four

9 * 8 * 7 * 5 = 2520

So you don't need the smaller divisors because you already have them.

BTW, great blog! Say hi to A from me and Wendy
JJoos
JJoos
1/29/2010 5:18:10 PM #
I get and appreciate your exercise, it's only a bit of overkill in this instance.

Alternatively you could just get the prime factors of each number:

9 = 3**2
8 = 2**3
7 = 7
6 = 2*3
5 = 5
4 = 2**2
3 = 3
2 = 2
1 = 1

And find the number with the superset of all those above:
answer = 1 * 2**3 * 3**2 * 5 * 7 = 2520

Thank you for giving me a blog post to comment on!
1/29/2010 7:52:32 PM #
for (var divisor = 1; divisor <= 9; ++divisor )
what if you do it the other way around:
for (var divisor = 9; divisor >= 1; --divisor )
...because if the number is divisible by 2 or by 3...the loop will go on, but it might not be divisible by 8 or 9, while if you go the other way, if the number is divisible by 9 or 8 it will be definitely divisible by 3 or 2.

and even shorter ... the loop could be:
for (var divisor = 9; divisor >= 5; --divisor )  -- hope you get why Laughing

cheers
1/29/2010 8:01:06 PM #
Good point guys... from a math perspective, my solution isn't optimal.

I guess I found it a good excuse to play with js.Fiddle & JavaScript ;)

I should have made it more generic so you could pass in a list of numbers you wanted to test or just factor out the redundant divisor in a given range.

Thanks for your suggestions.

Ryan Campbell
Ryan Campbell
1/29/2010 8:55:09 PM #
We're standing on your shoulders, Elijah Wink

Here is my solution, which accepts an arbitrary range and executes in O(n).

http://jsfiddle.net/DfQmp/

Intuitively, I think it could be rewritten to be O(n/2), but I can't prove it.

JSFiddle looks like an awesome product.  How long till all dev is done in a browser?  
1/29/2010 9:23:37 PM #
Nice Ryan... thnx for the update!

I took the liberty of updating your update to use a slider ;)

http://jsfiddle.net/DfQmp/2/
1/29/2010 9:39:36 PM #
@Ryan...you solution is wrong :d

if you choose 1..10 the result is 5040...although the correct result is still 2520

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading