Prime Number Function

Hi guys, I have a school projet for which I am supposed to make a function that will determine all the prime numbers between 3 and variable N.

When I run the program as is it is giving me every odd number and only seems to test for numbers divisible by 2.

Can someone point out where my mistake is?

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>
using namespace std;

void checkPrime (int numToCheck);

int main()
{
    int maxValue;
    cout << "This program gives the prime numbers between 3 and maxValue.\n";
    cout << "please enter a value into maxValue: ";
    cin >> maxValue;
    for (int N = 3; N < maxValue; N++)
    {
        checkPrime(N);
    }

    return 0;
}

void checkPrime (int numToCheck)
{
    for (int J = 2; J < numToCheck; J++)
    {
        if (numToCheck % J == 0)
            break;

        if ((numToCheck % J != 0) && (J = numToCheck - 1))
        {
            cout << numToCheck;
            cout << " is prime! \n";
        }
    }


}
Last edited on
(J = numToCheck - 1)

This is assigning J the value of numToCheck - 1, and then converting "numToCheck - 1" into a boolean value, which evaluates to true unless numToCheck is 1 (because 1-1 is 0).

Perhaps you meant to do J == numToCheck - 1.
You only need to check the odd numbers, and you only need to go up to the square root.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

bool checkPrime(int num);

int main() {
    cout << "Prints prime numbers between 3 and maxValue.\n";

    cout << "Enter a value into maxValue: ";
    int N;
    cin >> N;

    for (int i = 3; i <= N; i += 2)
        if (checkPrime(i))
            cout << i << ' ';
    cout << '\n';
}

bool checkPrime(int num) {
    for (int i = 3; i * i <= num; i += 2)
        if (num % i == 0)
            return false;
    return true;
}

Last edited on
Topic archived. No new replies allowed.