0
//Hi all,can you explain how to call this function in main.
//i ask user to enter the number,like this is it correct in main,recursevely call function?

 bool isPrime(int n, int d);
int main()
{
int number;
cout <<"Enter number >= 1";
cin >> number;
if(isPrime(number))
   {
     return 
      cout << "Yes";
      else
      return
      cout << "No";

    }
    return 0;
}
    bool isPrime(int n, int d)
    {
        if(n<2)
            return 0;
        if(d == 1)
            return true;
        else 
        {
            if(n % d == 0) 
                return false;
            else
                return isPrime(n, d - 1);
        }
    }

Edited by aluhnev

2
Contributors
2
Replies
20
Views
3 Years
Discussion Span
Last Post by aluhnev
0

You would need to call isPrime() with two numbers, one the number you are checking and the other a number smaller than that but larger than it's square root.

I would reccomend changing the name of isPrime() to primeTest() and having a second function called isPrime(), which takes only one int as its argument. This would call primeTest() with some appropriate argument automatically, so that the main() function can pass only the number being tested as the argument to isPrime().

#include <iostream>
#include <cmath>

bool isPrime(int n);
bool primeTest(int n, int d); 

int main()
{
int number;
cout <<"Enter number >= 1";
cin >> number;
if(isPrime(number))
   {
     return 
      cout << "Yes";
      else
      return
      cout << "No";

    }
    return 0;
}

isPrime(int n)
{
    if (n < 2)
    {
       return false;
    }
    else if (n == 2)
    {
       return true;
    }
    else
    {
        return primeTest(n, (int) ceil(sqrt(n));
    }
}

bool primeTest(int n, int d)
{
    if(n<2)
        return false;
    if(d == 1)
        return true;
    else 
    {
        if(n % d == 0) 
            return false;
        else
            return isPrime(n, d - 1);
    }
}

The sqrt() function returns the square root of a number as a double, and the ceil() rounds the number up to the next integer value. the (int) is a cast to make the double an int.

Edited by Schol-R-LEA

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.