Rikas
Rikas

Reputation: 187

program giving wrong output for a specific input

I want to check if a number is prime. Here is my code:

#include <iostream>

using namespace std;

int main(){
    int num;
    int i, k = 0;
    cin >> num;
    for(i = 2; i < num; i++){
        if(num % i == 0){
            k = k + 1;
        }
    }
    if(k > 0){
        cout << "The number is not prime" << endl;
    }else{
        cout << "Prime!" << endl;
    }
    return 0;
}

When I enter 6 , 78, ... etc it's giving the correct output. But when I'm entering 4294967296 which is not a prime number, it's returning Prime!.

Upvotes: 0

Views: 90

Answers (2)

Slava
Slava

Reputation: 44238

You need to validate your input. 4294967296 is too big for 32 bit signed integer, so std::cin truncates it to 2147483647 which is actually prime. You can check that printing your number back to screen. You should also change your loop to:

for(i = 2; i < num / 2; i++)

as it would provide the same result, but decrease calculation time twice.

Upvotes: 1

Barry
Barry

Reputation: 302718

That's because 4294967296 is a rather special number. It is 2^32, which is limit of the storage capacity of an int, which typically holds only 32 bits. Thus, your num is interpreted as if it were 0.

The rest follows logically from that overflow misinterpretation. The for loop is never entered, since 2 is not less than 0, so k never gets incremented.

EDIT Actually, in this particular case, it fails for a different reason. std::cin performs truncation on the input, so when you enter 4294967296, num will actually get assigned the value of 2147483647. Your program [correctly] prints that that value is prime. It's just that that's not the number the user had intended to test.

Upvotes: 4

Related Questions