开发者

How to create a loop 1M with random numbers >100000

My teacher asked me to create a loop that will be executed 1M times. I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different me开发者_如何学JAVAthod?

this is the code:

start_time = clock(); 
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");

This the gcd:

int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}


There is nothing wrong with having a loop that runs from 0 to 1000000. The reason that your program is crashing is something else that you are doing in your program.


Try one of the following:

  • Step through the code in the debugger to find which line is crashing.
  • Comment out lines in the loop (and after it) until it runs. Then uncomment things one by one to track down the culprit.

One suspcious thing I see off the bat: What type is elapsed_time declared as? You are doing what looks like integer (or quadword integer?) math on it, and then you tell printf to print it as a float. printf doesn't do intelligent type conversions for you or anything. If you feed it a variable of the wrong type, you are liable to get garbage, or a crash.


in gcd

you have an extra close brace

if x == y then z is undefined; so bad things can happen


Try your loop as

for (i = 0; i < 1000000; i++) {
   do num1 = rand(); while (num1 == 0);
   do num2 = rand(); while (num2 == 0);
   gcd1(num1, num2);
}

rand() can return 0. When it does that (after more than 10000 loops), your program will set z to 0 and attempt to divide by 0.


use longs, to loop over longer ranges:

for (long i = 0; i < 1000000L; i++) {
    //do something
}

for large randoms, you could cast the return of rand() to long and multiply two together or something like that. (Heh, probably showing my age by this answer... back when I was coding C regularly, int was only 16 bits. ;)


In this statement

while((x%z!=0) or (y%z!=0));

my compiler i(llvm-gcc-4.2) won't compile it. I'm just learning c but I think you want to change the "or" to "||"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜