Need to understand this.....:)

Cant understand this.........

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cmath> //To use sqrt
using namespace std;

bool IsPrime(int num)
{
    if(num<=1)
        return false;
    if(num==2)
        return true;
    if(num%2==0)
        return false;
    int sRoot = sqrt(num*1.0);
    for(int i=3; i<=sRoot; i+=2)
    {
        if(num%i==0)
            return false;
    }
    return true;
}

int main()
{
    cout << "Please enter a number to ckeck it : " ;
    int Number ;
    cin >> Number;

    if (IsPrime(Number))
        cout << "Wow this is a prime number ... " << endl;
    else
        cout << "O.o This is not a prime number :(" << endl;

    cin.get();
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cmath> //To use sqrt
using namespace std;

bool IsPrime(int num)
{
    if(num<=1) // if number is less than one
        return false; //return 0 to the caller
    if(num==2)// if number is equal to two
        return true;//return 1 to the caller
    if(num%2==0) // if the remainder of the number divided by two is zero
        return false;// return 0 to the caller
    int sRoot = sqrt(num*1.0);// Declare variable that is equal to the squareroot of the number times by one.
    for(int i=3; i<=sRoot; i+=2)//for i = 3 and i is less than or equal to the squareroot of the number, add two each time
    {
        if(num%i==0)// if the number divided by i has no remainder 
        return false;//then return 0 to caller
    }
    return true;// or else it will return 1
}

int main()
{
    cout << "Please enter a number to ckeck it : " ;// outputs question to console
    int Number ;// declares integer variable
    cin >> Number;// waits for user to input variable

    if (IsPrime(Number))//calls the function with users number as parameter inside if statement
        cout << "Wow this is a prime number ... " << endl;// if returns 1 output statement to console
    else
        cout << "O.o This is not a prime number :(" << endl;//if returns 0 output statement to console

    cin.get();//used to pause
    return 0;
}

also if you were wondering what the function actually does which im presuming you were.

It takes the number and finds the square root of it.
The number is then divided by any number under the square.
If the modulus(%) of the number is 0 then it is divisible.
If none of these numbers are divisible then it must be a prime number.

This probably explains it better
http://www.wikihow.com/Check-if-a-Number-Is-Prime
Topic archived. No new replies allowed.