-1

I have written following program to check if given number is prime or not. But somehow program gives multiples of 5 like 15,25 as prime numbers. Where is bug?

#include <stdio.h>

int main() {
    int number, i;

    printf("Enter the number to be checked\n");
    scanf("%d", &number);
    for (i = 2; i < number / 2; i++) {
        if (number % i == 0) {
            printf("The given number %d is not a prime number \n", number);
            break;
        } else {
            printf("The given number %d is a prime number \n", number);
            break;
        }
    }
    return 0; 
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 4
    Welcome to Stack Overflow! It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Paul R Dec 30 '15 at 18:27
  • In fact, it reports any odd number as prime. – Scott Hunter Dec 30 '15 at 18:32
  • You have to test *all* the divisors before you can report it as prime, not just the first divisor. – Weather Vane Dec 30 '15 at 18:33
  • My [previous answer](http://stackoverflow.com/questions/34455888/prime-numbers-in-c-language/34456837#34456837) which shows two different methods. – Weather Vane Dec 30 '15 at 18:35
  • Take out the second else statement and only report prime if it gets all the way through the loop. – Peter L. Dec 30 '15 at 18:35
  • @new_programmer Take into account that you marked a bad code as the best answer.:) – Vlad from Moscow Dec 30 '15 at 18:57

5 Answers5

1

You should use a flag to know when it's a prime number (Or it will break as soon as it test a single number that's not divisor of number)

bool isPrime = true;
for(i=2;i<number/2;i++){
    if(number%i==0)
    {
      isPrime = false;
      break;
    }
}
if (isPrime){
    printf("The given number %d is a prime number \n",number);
}
else {
    printf("The given number %d is not a prime number \n",number);
}
Mr. E
  • 2,070
  • 11
  • 23
0

Remove the else part from for and put these lines after the loop

if( i == number/2)
    printf("The given number %d is a prime number \n",number);
haccks
  • 104,019
  • 25
  • 176
  • 264
0

This code has lot of problems

#include<stdio.h>
int main()
{
  int number,i;
  printf("Enter the number to be checked\n");
  scanf("%d",&number);
  for(i=2;i<number/2;i++){
    if(number%i==0)
    {
      printf("The given number %d is not a prime number \n",number);
      break;
    }
    else
    {
      printf("The given number %d is a prime number \n",number);
      break;
    }
  }
  return 0; 
}

Say you entered 5, so it enterd for loop first iteration i=2

if(number%i==0) i.e 5%2==0 which is obviously false now your code goes to else condition and print and break

So what this break do is, it stops execution of innermost loop, as u have only one loop your execution stops and hence you get wrong answer not just for multiples of 5 but for many other inputs.

else condition should not be inside loop

A simple code would be

 #include <stdio.h>
    int main()
    {
      int n, i, flag=0;
      printf("Enter a positive integer: ");
      scanf("%d",&n);
      for(i=2;i<=n/2;++i)
      {
          if(n%i==0)
          {
              flag=1;
              break;
          }
      }
      if (flag==0)
          printf("%d is a prime number.",n);
      else
          printf("%d is not a prime number.",n);
      return 0;
    }

You should learn how to use if-else conditioning and use of break statements

Rajnish
  • 419
  • 6
  • 21
0

There are several bugs in the program.

The first one is that you do not check whether the entered number is positive. So if the user will enter a negative number the program will report nothing.

The second bug is that if the user will enter 1, 2, 3, or 4 then the program again will report nothing.

The third bug is that you exit the loop after its first iteration.

Take into account that according to the C Standard function main without parameters shall be declared like

int main( void )

The program can look the following way

#include <stdio.h>

int main( void )
{
    unsigned int number = 0;

    printf("Enter the number to be checked: ");
    scanf( "%u", &number );


    int prime = number == 2 || ( number % 2 && number != 1 );

    for ( unsigned int i = 3; prime && i <= number / i; i += 2 )
    {
        prime = number % i;
    }

    if ( prime )
    {
        printf( "The given number %u is a prime number \n", number );
    }
    else
    {
        printf( "The given number %u is not a prime number \n", number );
    }

    return 0; 
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • @chqrlie It is a typo that the initial value of i was 2. As for the scanf then there is no need to check the result because number is initialized by 0. – Vlad from Moscow Dec 30 '15 at 19:16
  • 1
    *"no need to check the result [of `scanf`]"* is poor advice for beginners. – Weather Vane Dec 30 '15 at 19:26
  • @WeatherVane In my opinion it is a very good advice for a beginner.:) When he will learn scanf in detail he can use some other approach. There is no any need to make the program more complicated. – Vlad from Moscow Dec 30 '15 at 19:28
  • Start as you mean to continue. – Weather Vane Dec 30 '15 at 19:31
  • @WeatherVane Among presented here programs my program is the best.:) Nobody can write such clear code as me, unemployeed.:) – Vlad from Moscow Dec 30 '15 at 19:34
  • Your *perfect* code fails for prime number `4294967291`. It prints `The given number 4294967291 is not a prime number`. – chqrlie Dec 30 '15 at 20:47
  • @chqrlie 4294967291 is not valid object of type unsigned int. If it is very important to you to check the valid input you can to complicate the code of the input. But it has nothing common with the code that determinates whether a number is prime. – Vlad from Moscow Dec 30 '15 at 21:17
  • @VladfromMoscow: You must be kidding, `4294967291`, in hex `0xfffffffb` is a perfectly valid 32 bit `unsigned int`... I'm assuming your machine `int` has at least 32 bits `;-)` – chqrlie Dec 30 '15 at 21:20
  • @chqrlie Oh, I forgot that it is unsigned int. I refered to INT_MAX.:) – Vlad from Moscow Dec 30 '15 at 21:51
  • @VladfromMoscow: yes, the problem is integer overflow, `4294967291` is larger than the largest 32 bit square. Using a division is much slower. There is a clever method for a single test for all `unsigned int` values: `i * i - 1 < x`. – chqrlie Dec 31 '15 at 05:17
0

So, a couple of things...

The main problem is that you're breaking out of your loop early whether the number is divisible by i or not:

if ( num % i == 0 )
  break;
else
  break;

You only want to break out of the loop early if the number is evenly divisible by i; otherwise, you check the against the next value of i:

for ( i = 2 ; i < number/2; i++ )
{
  if ( num % i == 0 )
    break;
}

After the loop, check to see if i is less than number / 2; if it is, then number is not prime:

if ( i < number / 2 )
  // number is not prime
else
  // number is prime

There are a couple of ways you can speed up your primality test. First of all, you only need to test up to the square root of number, rather than number / 2. Secondly, you can eliminate checks against even numbers; if a number is divisible by 2, then it's divisible by any even number, so you only need to check against 2 once. In code:

int prime = 0; // initially false

if ( number == 2 ) // 2 is a special case, check separately
{
  prime = 1;
}
else if ( number < 2 || number % 2 == 0 )
{
  prime = 0; // negative numbers, 0, 1, and even numbers are not prime
}
else
{
  prime = 1; // assume prime to begin with
  for ( int i = 3; prime && i * i < number; i += 2 ) // continue while prime is true
  {                                                  // and i is less than sqrt(number)
    prime = number % i;
  }
}

printf( "%d is%s prime\n", number, prime ? "" : " not" ); 
John Bode
  • 119,563
  • 19
  • 122
  • 198