-2

I have the following loop in main()

while (count < 5){
            //with 2^15 as the lower limit
                srand(time(NULL));
                ran_num = rand() % (65536 - 32769); //check READ ME Citation A
                ran_num += 32769;
                binary = Integer_to_Binary(ran_num);
                count += Primality_Test(ran_num, binary, sizeof(binary));
            }

The printf statement is in the Primality_Test function...

int Primality_Test(unsigned __int128 ran_num, int binary[], int num_bits){
    int result = Modular_Exponentiation(ran_num, binary, num_bits);
    if (result == 1){
        //the number is prime
        printf("[%d] passes the primality test as prime\n", ran_num); //print binary array too
        return 1;
    }
    else{
        //call Charmichael_Test
        result = Charmichael_Test(ran_num);
        //check for errors
        if (result == 1){
            //number is prime
            printf("[%d] is a charmichael number\n", ran_num);
            return 1;
        }
        else {
            //number is not prime
            //printf("This number is not prime");
            return 0;
        }
    }

}

my output is always the same number even though when I debug it, ran_num is being changed

[57221] is a charmichael number
[57221] is a charmichael number
[57221] is a charmichael number
[57221] is a charmichael number
[57221] is a charmichael number
Kendall Weihe
  • 111
  • 1
  • 1
  • 9

2 Answers2

1

Because you call srand() in the loop. You use time(NULL) which gives time in seconds, so probably the same value for each of your 5 loops. And as srand() sets the "starting" point of rand() sequences, you have the same value.

Extract srand() outside the loop.

Note that with a very large value for your loop you will see a change in printed value each second.

hexasoft
  • 677
  • 3
  • 9
0

Because you call srand() inside the loop. You always reset the random seed in each iteration because time() has seconds precision and the time between two iterations is hardly close to 1 s.

You should call srand() just once at the very begining of the program, preferrably in the main() function.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97