[英]C++ program to compute lcm of numbers between 1 to 20 (project euler )
如標題所示,這是一個查找1至20之間1cm數字的程序。我找到了一種算法來執行此操作,這是鏈接
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml網頁上有一個Java小程序,可以更好地解釋算法
問題 :我編寫的代碼編譯器沒有顯示任何錯誤,但是當我運行代碼時,程序發瘋了,我猜可能是一些無限循環,但我無法終生解決。 我使用的是turbo c ++ 4.5,所以基本上,如果有人可以看一下代碼並幫助我,那就太好了。 提前致謝
算法 :
說我們需要找到2,6,8的lcm
首先,我們找到該序列中的最小數,並在其上添加數字,即該序列變為
4,6,8
現在我們再次找到最小值,並在列中添加初始值,即2
6,6,8
所以下一次迭代變成
8,6,8
8,12,8
10、12、8
10、12、16
12,12,16
14,12,16
14,18,16
16,18,16
18、18、16
18、18、24
20,18,24
20,24,24
22,24,24
24,24,24
如您所見,所有數字都等於1,即我們的lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
在這一行:
a[j]=k+b[j];
您使用j
但它被單位化,因此它是一個巨大的值,並且您不在數組范圍內,因此會遇到分段錯誤。
您的代碼中還會發生一些奇怪的事情。 void main()
並且您使用cout
而不用說std::cout
或using namespace std;
或類似的東西。 一種奇怪的做法。
另外,如果您要使lcm()
為函數,您是否不認為應該將數組作為參數傳遞? 那就是int lcm(int a[], int b[]);
。
您可能還會考慮使用調試器並改善編碼實踐。 我在調試器的幫助下將代碼粘貼到編譯器的30秒內發現了此錯誤。
您的循環條件是:
while(n==1&&i<20)
因此,您的equl
函數將永遠不會返回1,因為如果n恰好是1,則循環將繼續進行並且永遠不會返回1。但是,您的程序似乎仍未返回正確的結果。 您可以拆分一段代碼以找到最小的元素,並用它替換以保持整潔:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
然后您可以說j = least(a, 20);
。 我將把您程序的進一步工作留給您。 考慮將變量稱為有意義的變量,而不是i,j,k,a,b
。
您的equl
函數正在使用0-20的數組索引,但是數組只有1-19
如果第一個元素最小,則lcm()
j
未初始化。 在while循環的頂部應將其設置為0
在以下代碼中,當i = 19時,您正在訪問a[20]
,它不在數組的范圍之內。 應該for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
您實際上並沒有為cout
使用std
名稱空間。 這應該是std::cout<<l
您包括iostream.h
。 該標准是不帶.h的iostream
,這可能不適用於這樣的舊編譯器
而不是在各處硬編碼20,您應該使用#define
。 這不是錯誤,只是樣式問題。
以下代碼不執行任何操作。 這是默認行為
else
continue;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.