0

I am a complete beginner and was just trying to apply what I have learned.

So I tried to make a C program that computes if a number passes the prime test in Fermat's little theorem.

Here is the code:

#include <stdio.h>
#include <math.h>

int main() {
  double p, a, t;
  printf("Enter the number tested to be prime: ");
  scanf("%lf", &p);
  a = 1;
  t = 0;
  while (a <= p && t == 0) {
    t = pow(a, p) - a;
    t = (int)t % (int)p;
    a++;
  }
  if (t == 0) {
    printf("prime test passed");
  } else {
    printf("prime test failed");
  }

  return 0;
}

So the problem is it works great until 10, but after that when I try it for 11 it just fails the test. Why is this happening?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
khoprutu
  • 11
  • 2

1 Answers1

1

for 11 it just fails the test. Why is this happening?

The reason for this concrete failure is likely not due to use of floating point math, but quite the contrary due to use of casting to an integer type by (int)t with a 4-byte int. In the course of your prime test, double t is assigned the value 811−8 = 8589934584, which can well be held in t, but not in an int with a maximum value of 231−1 = 2147483647.

Of course all this does not mean that you'll get much further if you just take this hurdle; soon you'd really encounter problems of floating point math. So the comment from Bob__ may indeed be a good advice.

Armali
  • 18,255
  • 14
  • 57
  • 171