• Finding the nth prime number using function in "C"

    Ganesh Member

    Hello, I need help with simplifying my code by creating a prototype, a function, and a function definition. This is what my code looks like and i need to replace the code between the two comment lines with a function called, check_if_prime();

    #include 
    #include 
    #define TRUE 1
    #define FALSE 0
    //function prototype goes here
    int main(void)
    {
    unsigned int nth_prime, number_of_primes;
    unsigned int test_int, divisor;
    _Bool isPrime;
    
    printf("Enter the nth_prime to find: ");
    scanf("%u", &nth_prime);
    
    test_int = 1;
    number_of_primes = 0;
    
    do
    { test_int++;
    
    isPrime = TRUE;
    
    for(divisor = 2; divisor 
        
  • Adelaid Member

    Here is solution

    #include 
    #include 
    using namespace std;
    bool check_if_prime(int n);
    int main()
    {
    unsigned int nth_prime, number_of_primes;
    unsigned int test_int;
    
    printf("Enter the nth_prime to find: ");
    scanf("%u", &nth_prime);
    test_int = 1;
    number_of_primes = 0;
    
    do
    {
       test_int++;
       if (check_if_prime(test_int) == true)
          number_of_primes++;
    }
    while(number_of_primes < nth_prime);
    printf("The %u Prime Number = %u\n", nth_prime,test_int);
    
    return 0;
    }
    bool  check_if_prime(int n)
    {
       bool isPrime = true;
       int divisor;
       for(divisor = 2; divisor < n; divisor++)
       {
          if(n % divisor == 0)
          {
             isPrime = false;
             break;
          }
       }
       return isPrime;
    }
    
  • ShikhaTan Member

    Why did you take out the definitions of TRUE and FALSE in the beginning. I also tried adding #include but it it doesn’t recognize that command. Everything else looks clear to me.

  • Amit Member
    #include 
    #include 
    #define TRUE 1
    #define FALSE 0
    #define _Bool int
    _Bool check_if_prime(int n);
    int main()
    {
    unsigned int nth_prime, number_of_primes;
    unsigned int test_int;
    
    printf("Enter the nth_prime to find: ");
    scanf("%u", &nth_prime);
    test_int = 1;
    number_of_primes = 0;
    
    do
    {
       test_int++;
       if (check_if_prime(test_int) == TRUE)
          number_of_primes++;
    }
    while(number_of_primes < nth_prime);
    printf("The %u Prime Number = %u\n", nth_prime,test_int);
    
    return 0;
    }
    _Bool check_if_prime(int n)
    {
       bool isPrime = TRUE;
       int divisor;
       for(divisor = 2; divisor < n; divisor++)
       {
          if(n % divisor == 0)
          {
             isPrime = FALSE;
             break;
          }
       }
       return isPrime;
    }
    
Viewing 3 reply threads
  • You must be logged in to reply to this topic.
en_USEnglish