How to Find a Prime Number Using C++ Code

Prime numbers are the natural numbers that are greater than one and they are divisible by itself and 1 only for example 7 is a prime number. Deciding about a prime number which is not very large is easy but if you are presented by a very large number to tell that weather it is a prime number or not is very difficult task. You can create small C++ software or a program which will tell you whether the number is a prime number or not. Following is the step by step guide to teach you how you can write a C++ code to decide about a prime number.

Instructions

  • 1

    I am assuming here that you have basic know how of C++ so I will only describe the steps related to finding a prime number.
    First of all make sure you have included all of the basic libraries so that code does not throw an error.

    I am assuming here that you have basic know how of C++ so I will only describe the steps related to finding a prime number.First of all make sure you have included all of the basic libraries so that code does not throw an error.

  • 2

    In order to find whether a number is prime or not we need to write a small function or method to do the calculations about the prime number. For this in you C++ code write the following method.


    int diviser_search(int   natural_number)
    {
    int calculation = 2;
    while (calculation <  natural_number      &&  natural_number   %  calculation  !=  0)
    {
    calculation = calculation +1;
    }
    Return (calculation);
    }

  • 3

    The above will take a natural number as input and then it will check in the while that weather it is greater than 1 or not and it will also check the natural number’s modulus calculation that whether it is completely divisible by any number other than one or not.

  • 4

    Now we will write the main method for our program. It will take a number as an input from user and then it will pass the number to the method we defined above.


    int main () {

    int a;


    cout <<”Please enter a number:  ” ;


    cin >>  a;


    int check == diviser_search (a);


    if(check  ==  n)
    {
    cout<<”number is prime”<
    }


    else
    {
    cout<<”number is not prime”<
    }


    return 0;

    }











  • 5

    Just write that code in your compiler and then compile and run it. Every time you need to find about a prime number or a composite number simply use this code.

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 2 = seven