//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);
        }
    }

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.

Thank you for explanation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.