GoodJeans
GoodJeans

Reputation: 380

How to find prime numbers

Hi I'm writing in c language, below is my code. I'm trying to take in an input to check whether the person keying in a number is a prime number by using modulus. However I'm getting error at the first if statement. The error is floating point exception(core dumped) why is this so? Am I not allowed to compare values with 0?

#include <stdio.h>

int main()
{
  int i = 0, j = 0, count = 0, value = 0, stop = 0;

      scanf("%d", &j);
      stop = j;
    for(i = 0; i < stop; ++i)
    {
      value = j % i;
      if(value == 0)
      {
        ++count;
      }
    }
    if(count>1)
      {
      printf("YES");
      }
      else
      printf("NO");
            return 0;

}

Below is my question actually, I am not able to get my compile to work right although I can get the output. Input

t – the number of test cases, then t test cases follows. [t <= 500] Each line contains one integer: N [2 <= N <= 2^63-1] Output

For each test case output string "YES" if given number is prime and "NO" otherwise.

#include <stdio.h>

int main()
{
  int i = 0, j = 0, count = 0, value = 0, stop = 0, store[]={0}, s = 0;

      scanf("%d", &j);
      stop = j;
    for(i = 1; i < stop; ++i)
    {
      value = j % i;
      if(value == 0)
      {
        store[s]=value;
        ++count;
        ++s;
      }
    }

    if(count>=2 || j==1 )
      {
      printf("NO");
      }
      else
      printf("YES");
    return 0;
}

Upvotes: 0

Views: 121

Answers (1)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16650

I bet, you get the error ahead of the if statement at:

value = j % i;

This is, because you start with i = 0:

for(i = 0; i < stop; ++i)

Since the modulo operator % is a division, using 0 as second operand isn't legal. You get a divide by zero error.

BTW: Starting with 1 is meaningless.

Upvotes: 1

Related Questions