0
#include<stdio.h>
#include<stdlib.h>
int is_prime(int num)
{
    if (num <= 1) return num;
    if (num % 2 == 0 && num > 2) return num;
    for(int i = 3; i < num / 2; i+= 2)
    {
        if (num % i == 0)
            return num;
    }
    return 0;
}
void main()
{
    while(1)
    {
        int r = rand();
        if(r==is_prime(r))
        {
            printf("The number is %d",r);
            break;
        }
    }
}

I tried this code to generate a random prime number. But it's giving the same number every time and the number is not prime. What's the error in this program?

  • this is how `rand` works without call to `srand` https://www.geeksforgeeks.org/rand-and-srand-in-ccpp/ – Iłya Bursov May 12 '18 at 05:56
  • your `is_prime` function is incorrect. `if (num % 2 == 0 && num > 2) return num;` is a completely wrong condition. every even number > 2 will be returned as prime. – Afshin May 12 '18 at 05:59

0 Answers0