BpVx
BpVx

Reputation: 23

How to check if a number is prime in C++

to me this code looks correct, but when i run it all the output it gives me is "2". I've tried looking it over several times but each time i don't find anything wrong. So I'm wondering if someone wouldn't mind looking over the following code to let me know what I am doing wrong.

#include <iostream>

using namespace std;

bool oddOrEven(int x)
{
    int divisor = 2; // initial divisor check
    bool boolCheck = true; // initial boolean value set to true, later to check

    for(int i = x-1; i >= 2;i--)
    {
        if(i%divisor == 0)
            boolCheck = false;
    }

    return boolCheck; // returning whether or not the number is prime
}


int main()
{
    int num1 = 0;

    cout << "Please enter how many numbers you want to check: " << endl;
    cin >> num1;

    cout << "Prime numbers from 2-" << num1 << endl;

    for(int i=num1; i >= 2; i--)
    {
        if(oddOrEven(i))
            cout << i << endl;
    }
}

Any help would be appreciated, I feel like it might have something to do with my bool check, but I'm not 100% what.

EDIT: Before even posting this i realized i did not increase the divisor, so i tried that and it's still not coming out right. All i changed was this:

for(int i = x-1; i >= 2;i--)
{
    if(i%divisor == 0)
        boolCheck = false;
    divisor = divisor + 1;
}

So I am still stuck, once again any help is appreciated.

Upvotes: 0

Views: 1077

Answers (1)

Anton Savin
Anton Savin

Reputation: 41321

You are dividing wrong numbers. Change this line

if(i%divisor == 0)

to

if (x % i == 0)

That being said, as you probably know your algorithm is far from optimal. At least you can return false immediately instead of setting the flag. You can check divisors only up to square root of x. You can check only odd divisors. And so on.

Upvotes: 3

Related Questions