我一直試圖通過素分解實現L.C.M(1,2,...,20)的C語言。我在谷歌搜索了所有,但他們只是兩個變量的方法。 我寫這段代碼:如何使用遞歸或其他方法實現L.C.M(1到N),N> 2?
int lcm(int a[i],int n)
{
//n is the nth number to find L.C.M, for eg: LCM(1,2,...,20) Here,N=20
//a[i] is the list of primes upto n;
K=sqrt(n);
while(pow(a[i],k)>n)
K=K-1;
P=P*pow(a[i],k);
/*My idea over here is to make a list of primes up to 'n' and store them in list a[i]. Then for each each prime in the list,the power of that prime should exceed 'n'.
For eg: Let, N=10 .. K=3 ,
Pow(2,3)=8<10
So,P=1*8,and for the remaining primes {3,5,7},it can be represented in prime factorization:
P=2^3 * 3^2 * 5^1 * 7^1 = 2520.
}*/
我在實施它的問題,因爲我不知道很多關於數組,我認爲這種算法並不那麼有效。 我很感興趣的是使用遞歸或任何其他有效的方法找到LCM(1到N)。請幫助!
如果我想計算LCM(1,2,3 ... 10),那該怎麼辦? 有沒有一種算法可以計算LCM到N? – 2015-03-09 04:41:11
@VanuAparna是的,請參閱我的答案的第1部分。你從'L = 1'開始,然後從'i = 1'循環到'10',並在每一步讓'L = LCM(L,i)'。 '最後返回L'。 – 2015-03-09 04:43:08
我想我明白了。但是,您能否在代碼片段中顯示該邏輯,以便我能夠更好地理解。 – 2015-03-09 04:47:48