Primality test

Apr 12, 2019 at 3:10pm
This function seems to work for small number but fails with large number. Can anyone help me understand the problem. Thanks.

bool isPrime(int number)
{
for(int i = 2; i <= sqrt(number); i++)
{
if( number % i == 0)
return false;
}
return true;
}

int main()
{
for(int i = 2; i < 1000; i++)
{
if(isPrime(i) == true)
cout << i << endl; // this code to generate primes less than 1000 seems to work
}

long long number = 123456782122;
cout << isPrime(number); // THE RESULT FOR THIS STATEMENT IS TRUE. PLEASE HELP.

return 0;
}
Last edited on Apr 12, 2019 at 3:16pm
Apr 12, 2019 at 3:28pm
Hello kenke,



PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



The problem comes from the number that can be stored in a given variable type.

You may define the number as a "long long" in "main", but the function is expecting an "int". some of the number is lost when you try to store a "long long" into an int.

Hope that helps,

Andy
Apr 12, 2019 at 3:41pm
To make it apparently run
1
2
3
  long long number = 123456782122;
  int notsolong = number;
  std::cout << notsolong;

Result:
-1097269462 

For this figure your bool isPrime(int number) returns true.
Apr 12, 2019 at 3:45pm
Thanks Handy Andy! I found your advice for formatting helpful too.
Apr 12, 2019 at 4:22pm
long long number = 123456782122;
another issue is that some (most, all? darn if i know) need numerical suffixes to work properly. EG
long long number = 123456782122ull; //the ull is needed to prevent some compilers from making the value (int) first and then copying it into the long long (due to how constants are typeless and it has to guess the type, and some compilers just guess (int) here)

Apr 13, 2019 at 7:35am
another issue is that some (most, all? darn if i know) need numerical suffixes to work properly.
1
2
3
4
5
6
7
8
9
10
11
12
// Example program
#include <iostream>
using namespace std;

int main()
{
  long long number = 123456782122;
  int notsolong = number;
  std::cout << notsolong << "\n";
  std::cout << number << "\n";
  std::cout << number - 123456782122ull << "\n";
}

-1097269462
123456782122
0

I conclude: Some compilers may need numerical suffixes. Probably all work work properly with it. Who knows.
Apr 13, 2019 at 11:08am
Its part of the language and has been for some time (c-99 era? not sure?). You would have to work at it to find a compiler that did not work with them, eg the turbo 1.0 that some people use for dos 3.0 era code.
Topic archived. No new replies allowed.