[問題] 有關uva 100的問題

看板Programming作者 (好噁)時間14年前 (2011/11/08 14:50), 編輯推噓1(105)
留言6則, 3人參與, 最新討論串1/1
大家好~ 我是第一次用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

11/08 18:40, , 1F
用table存的目的就是不要再算一次吧?
11/08 18:40, 1F

11/08 18:40, , 2F
不過你不管怎樣都會算一次~
11/08 18:40, 2F
可是我有一行 if (table[n]) 這樣不是如果有就會找到了嗎@@

11/08 18:41, , 3F
runtime error應該是陣列讀取索引值超過了~
11/08 18:41, 3F

11/08 19:39, , 4F
n給的值不超過一百萬 但是計算過程中會超過
11/08 19:39, 4F

11/08 19:40, , 5F
999999 你把它乘三再加一就超出陣列範圍了
11/08 19:40, 5F
感謝兩位m大 我已經把陣列範圍的限制加入了 不過還是超過時間QQ 我再試試看好了 謝謝! ※ 編輯: howardxu 來自: 220.132.237.8 (11/08 22:55)

11/08 23:13, , 6F
成功了 忘記把debug的cout拿掉= =...
11/08 23:13, 6F
文章代碼(AID): #1EkD5FVX (Programming)
文章代碼(AID): #1EkD5FVX (Programming)