0

I have written a function that should check whether an integer is prime, using the Wilson theorem. However it outputs that 5 is not a prime number, which obviously is. I want to ask why is that?

#include <iostream>
using namespace std;
long int counter = 1;
bool primeWilson(int n)
{
    for(int i=1; i<n; i++)
    {
        counter*=i;
    }
    if(n%(counter+1)!=0)
    {
        return true;
    }
    return false;
}
A.Petrov
  • 71
  • 6
  • 1
    Note that the factorial you compute will quickly grow outside the range of an `int`, or any fundamental integral type in C++ for that matter. It's not a problem for 5, but it will almost certainly be for 20. – chris Jan 25 '18 at 08:18
  • Apart from the logical problem, you probably want to move the initialisation of `counter` into the function, in case you want to call it more often than once. Maybe the whole definition can be moved. – Yunnosch Jan 25 '18 at 09:06

1 Answers1

2

You are checking the wrong way around for implementing Wilson. For example:

25 is divisable by 5
but
5 is not divisable by 25

n%(counter+1)

->

(counter+1)%n
Yunnosch
  • 26,130
  • 9
  • 42
  • 54