user3148192
user3148192

Reputation: 39

Does this program have a limit?

I am having a problem with this code. Although it should say that this number is not prime, as i put a ridiculously large number that i know to be nonprime (252345435465, or even 1000000000000 as an example), it states that the number is prime.

#include "stdafx.h"
#include <iostream>
#include <cmath>

using namespace std;

int main() {
int n;
int i;
int prime = true;

cout << "Type in a number and press ENTER: ";
cin >> n;

i = 2;
while (i <= sqrt(n)) {
    if (n % i == 0) {
        prime = false;
        break;
    }
    i++;
}

if (prime)
    cout << "The number is prime" << endl;
else
    cout << "The number is NOT prime" << endl;

system("PAUSE");
    return 0;
}

Is there something I'm doing wrong?

Upvotes: 3

Views: 75

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145419

First, to avoid including the non-standard header <stdafx.h>, just turn off precompiled headers in your Visual C++ project (right click the project, then properties).

The main problem is that you're inputting values too large for the int type.

To detect that, simply check the state of the stream after the input operation:

#include <iostream>
#include <stdlib.h>  // EXIT_FAILURE
#include <cmath>

using namespace std;

int main() {
int n;
int i;
int prime = true;

cout << "Type in a number and press ENTER: ";
cin >> n;
if( cin.fail() )
{
    cout << "Sorry, that's not a valid `int` number." << endl;
    return EXIT_FAILURE;
}

i = 2;
while (i <= sqrt(n)) {
    if (n % i == 0) {
        prime = false;
        break;
    }
    i++;
}

if (prime)
    cout << "The number is prime" << endl;
else
    cout << "The number is NOT prime" << endl;

system("PAUSE");
    return 0;
}

Upvotes: 2

JBentley
JBentley

Reputation: 6260

A 32-bit signed int can take a range of values between –2,147,483,648 to 2,147,483,647. Your number is too large for that range.

Either use a more suitable variable type, or only input numbers which are within range for the variable you are using.

See this answer for more information on C++ data types and their ranges.

Upvotes: 1

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6049

The values you are putting in are too big for an int to hold. They are overflowing the 32 bit limit of a signed int (-2147483648 through 2147483647).

Upvotes: 2

Related Questions