Hi ;)
I wanted to write a program which would tell "YES" if an input number was prime, and "NO" if it wasn't.
Fermat’s Little Theorem: If n is a prime number, then for every a, 1 <= a < n,
a^(n-1) % n = 1
My program knows when a number isn't prime,but for some unknown reason when the input number is for example 7 the return is "NO".
This is how it works: https://ibb.co/pdqqb4J
??? What is the value of n when it gets to line 30?
1 2 3 4 5 6 7 8 9
int n, times;
cout << "How many numbers do you want to check?" << endl;
cin >>times;
cout << endl;
for(int k=0; k<times; k++)
{
bool check;
check = ifprime(n);
Well, I hoped the value was as in the input in function, but now i see it looks not so good.
Changed it to this below, but it still doesn't work as it should: (n value is input in main, not in function)
What output are you expecting for what input? (Please don't direct people to external pages for this.)
Please also put prompt lines in whenever you want an input. You may understand how your program works, but others may not (especially when your indentation is very inconsistent).
Are you sure that Fermat's Little Theorem is an "equivalence" statement; i.e. does
prime => property
necessarily mean that
property => prime
?
Now I'm not so sure that this theorem works backwards, thanks.
Maybe for now, I'm just curious why when the input number = 7, the program tells that
How many numbers do you want to check?
1
7
1%7 = 1 (1 power 6)
64%7 = 1 (2 power 6)
729%7 = 1 (3 power 6)
4096%7 = 1 (4 power 6)
15624%7 = 0 (5 power 6) <=== ???
NO
Why 15624, not 15625? In this line, the output should be 5 power 6, but it's missing one...
How many numbers do you want to check?
1
7
1%7 = 1
64%7 = 1
729%7 = 1
4096%7 = 1
15625%7 = 1
46656%7 = 1
YES
About the only thing I can suggest is that you are using pow() ... which naturally deals with floating point numbers, and so is subject to all those floating-point rounding difficulties. result = pow(a, n-1);
If this works out as, say, 15624.99999999
then it will truncate down to 15624
To get powers of integers ... just use repeated multiply, NOT pow()
Another advantage of using "repeated multiply ... modulo p" over the pow() function, is that successive multiplications modulo p will prevent blow-up. You will never end up with a number bigger than the original prime.