Tuesday, November 1, 2011

Solution to Project Euler Problem 5 - the smallest positive number that is evenly divisible by all of the numbers from 1 to 20

http://projecteuler.net/problem=5

Question:

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?

Answer: 232,792,560

Solution:
#!/usr/bin/perl -w
use strict;


my ($max,$i,$num,$found);
$max=20;
$num=2;
while($num) {
        $found=1;
        for ($i=2;$i<=$max;$i++)
        {
                print "$num%$i \n";
                if( ($num%$i) != 0 ) {
                        last;


                }else {
                        $found++;
                }


        }
        if($found == $max ) {
                print "The smallest number that can be divided by each of the nu
mbers from 1 to $max is:  $num \n";
                exit (0);
        } else  {
                $num++;
        }
}


Output:
The smallest number that can be divided by each of the numbers from 1 to 20 is:
 232792560

No comments: