The project Euler problem 5 is stated as : "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?" Here's the c++ code for the function I'm using.
long long unsigned int rangeLCM(int n)
{
long long unsigned int ans=1;
for(int i=1;i<=n;i++)
{
if(ans%i!=0)
{
if(i%(ans%i)==0)ans*=(i/(ans%i));
else ans*=i;
}
}
return ans;
}
The code works well for the example stated in the problem and the problem itself{rangeLCM(10)=2520
and rangeLCM(20)=232792560
}, but I think it's not perfect and is missing out on some edge cases.
Instead of actually calculating the LCM(ans,i)
, I have checked that the bigger of the two(always ans
) is divisible by i
. If not, then ans
is multiplied by a number equal to i/(ans%i)
or i
depending on whether i
is divisible by (ans%i)
or not.
This is based on the following facts:
LCM(8,12)=24=12*(8/(12%8));
LCM(9,30)=90=30*(9/(30%9)
LCM(7,13)=91=13*7
However, it fails for the following types of cases:LCM(8,14)=56 != 8*14
Yet, the code for rangeLCM gives the right output for all inputs I have tried yet. Why?