看板 Programming 關於我們 聯絡資訊
大家好~ 我是第一次用uva的online judge 寫程式也算是新手 這兩天試著用c++寫了uva編號100的程式 (3n+1那個) 自己跑的答案應該都沒錯 可是傳到uva後他說我的程式有run time error: Your submission with number 9449122 for the problem 100 - The 3n + 1 problem has failed with verdict Runtime error. This means that the execution of your program didn't finish properly. Remember to always terminate your code with the exit code 0. 我的程式碼如下: #include <iostream> using namespace std; #define SIZE 1000001 static unsigned short table[SIZE]={0}; unsigned short cycleLength(unsigned long n){ cout << "counting...: " << n << endl; if (n<SIZE && table[n]){ return table[n]; } if (n<SIZE){ if (n&1){ //odd table[n] = 1 + cycleLength((3*n)+1); return table[n]; } else{ table[n] = 1 + cycleLength(n>>1); return table[n]; } } else { // over table size if (n&1){ //odd return 1 + cycleLength((3*n)+1); } else{ return 1 + cycleLength(n>>1); } } } int main(){ unsigned long in1, in2; unsigned short temp=0; unsigned short max; table[1]=1; while(cin >> in1 >> in2){ if (in1<in2){ for (int i=in1; i<=in2; i++){ temp = cycleLength(i); if (temp > max) max = temp; } } else{ for (int i=in2; i<=in1; i++){ temp = cycleLength(i); if (temp > max) max = temp; } } cout << in1 << " " << in2 << " " << max << endl; max = 0; } return 0; } 可以請版上的高手們幫我看看嗎> < 第一次發文 如果有任何要改進的地方煩請告知 一定馬上改 謝謝大家!!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.132.237.8
kytu:用table存的目的就是不要再算一次吧?140.112.247.191 11/08 18:40
kytu:不過你不管怎樣都會算一次~140.112.247.191 11/08 18:40
可是我有一行 if (table[n]) 這樣不是如果有就會找到了嗎@@
kytu:runtime error應該是陣列讀取索引值超過了~140.112.247.191 11/08 18:41
chchwy:n給的值不超過一百萬 但是計算過程中會超過 220.134.128.54 11/08 19:39
chchwy:999999 你把它乘三再加一就超出陣列範圍了 220.134.128.54 11/08 19:40
感謝兩位m大 我已經把陣列範圍的限制加入了 不過還是超過時間QQ 我再試試看好了 謝謝! ※ 編輯: howardxu 來自: 220.132.237.8 (11/08 22:55)
howardxu:成功了 忘記把debug的cout拿掉= =... 220.132.237.8 11/08 23:13