While trying to submit my 3n+1 code, I keep on getting a runtime error although it works perfectly with a huge number of sample input. I've spent lots of time trying to spot the error but I can't find it. Can anybody help?
#include <stdio.h>
#define SIZE 10000
unsigned short countCycle(long num); /* prototype for a fn that gets int and returns the cyleLength */
unsigned short greatest,cyclyeLength; /* greatest for holding greatest cycyle */
unsigned short table[SIZE]; /* storing sequances with indecies up to 10,000 */
long temp;/* temp storage */
short flag;/* n>m or not */
int main (int argc,char* argv[])
{
long n,m,i;
while(scanf("%lu %lu",&n,&m) != EOF)
{
greatest = 0;
if(n>m)
{
temp = n; n=m; m=temp;
flag = 1;
}
for (i=n;i<=m;i++)
{
temp = countCycle(i);
greatest = (greatest>temp) ? greatest:temp;
}
if(flag == 1)
printf("%lu %lu %d\n",m,n,greatest);
else
printf("%lu %lu %d\n",n,m,greatest);
while(getchar() != '\n') /* clear the input stream */
continue;
}
return(0);
}
unsigned short countCycle(long num)
{
temp = num;
cyclyeLength = 0;
while(1)
{
if(num == 1)
{
cyclyeLength++;
if(temp<SIZE)
table[temp] = cyclyeLength;
return cyclyeLength;
}
if((num<SIZE) && (table[num]>0))
{
table[temp] = (cyclyeLength + table[num]);
return (cyclyeLength + table[num]);
}
if( num % 2 != 0 )
{
num = 3*num + 1;
cyclyeLength++;
}
if( num % 2 == 0 )
{
num/=2;
cyclyeLength++;
}
}
}