-2

I used the following code and it showed numbers like 49 as prime and not composite. I am new to programming so please help me with the correct code.

#include <stdio.h>
int main()
{
    int n;
    int i;
    scanf ("%d", &n);
    for (i=2; i<n; i++)
    {
        if (n%i==0)
        {
            printf ("number is composite");
        }
        else
        {
            i=i+1;
        }  
    }
    printf("number is prime");
    return 0;

}
Tarun Khare
  • 1,447
  • 6
  • 25
  • 43

7 Answers7

2

You can modify your loop as follows -

 if(n%2==0 && n!=2){                   //if 2's multiple is entered no need of loop just check this
      printf("number is composite");
      return 2;                        // for sake I just returned 2 
   }             
 for (i=3; i<n;i=i+2)
{
    if (n%i==0)                              // if this is true 
    {
        printf ("number is composite");      // print this   
        return 1;                            // return from function no further iterations 
    } 
}

In this way you stop loop as if condition is true and its code in its block us executed .

ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • Returning anything but zero from main usually indicates an error condition. Also, this can be optimized, it's enough to look for potential divisors up to `sqrt(n)`. – user4520 Oct 26 '15 at 09:56
  • @szczurcio Yeah, loop can be modified to got till `sqrt of n`. And its a convention to indicate success by `0` . We have to return anything , so why not `1`. – ameyCU Oct 26 '15 at 09:58
  • Why to check again by multiples of 2 when once checked by 2 ? – wrangler Oct 26 '15 at 09:59
  • @wrangler Took care of that . – ameyCU Oct 26 '15 at 10:04
2

You didn't stop the loop when you discovered that the number was composite, so composite numbers get both messages.

When i is not a factor of n you are adding 1 to i but then the for loop adds 1 again. This means that for every number that is not a factor of n you skip a number.

The printf("number is prime"); is not surrounded by any kind of if, so it will always be printed regardless of whether or not the number is actually prime. Unlike humans, computers won't think twice about printing conflicting information because computers are incapable of interpreting the actions we make them do.

You can optimize your code by checking less numbers. Only check up to the square root of the number.

This code is untested but should work. Note that this only eliminates the checking of factors above the square root, but not any multiples of previously checked factors (e.g. written like this, the program will check if the number is divisible by 2 but also by 4, 6, 8, 10, etc).

#include <stdio.h>
#include <math.h>
int main()
{
    int n;
    int i;
    int isComposite = 0;
    scanf ("%d", &n);
    for (i = 2; i <= (int)sqrt((double)n); i++){
        if (n % i == 0){
            printf ("number is composite");
            isComposite = 1;
            break;
        }
    }
    if (!isComposite){
        printf("number is prime");
    }
    return 0;

}
Arc676
  • 4,445
  • 3
  • 28
  • 44
1

You should remove i=i+1 line, you increment i already in for (i=2; i<n; i++)

After that, you must put your conditions after the loop for prevent print result at every check.

#include <stdio.h>
int main()
{
  int n;
  int i;
  scanf ("%d", &n);
  for (i = 2; i<n; ++i)
    {
      if (n%i==0)
        {
          printf ("number is composite, divisible by %d\n", i);
          break;
        }
      printf("i=%d\n", i);
    }
  if (n%i != 0)
    printf("number is prime\n");
  return 0;
}
Glastis
  • 163
  • 4
  • 15
0

Combining all suggestions and comments gives:

int q= (int) sqrt(n);
if (n%2==0)
{
    printf ("number is composite");      // print this   
    return 1;                            // return from function no further iterations 
}
for (i=3; i<=q; i += 2)
{
    if (n%i==0)                              // if this is true 
    {
        printf ("number is composite");      // print this   
        return 1;                            // return from function no further iterations 
    } 
}
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

the reason you are getting 49 a s composite is because of this line:

else
{
    i=i+1;
}

this causes you to skip odd numbers in your check, and 49 is 7*7, therefore the ouput yo get is that it is prime. Another problem you have is that you do not stop the loop when you get a composite number, and at the end of it you will invoke this line of code regardless of what happens in the loop. printf("number is prime");

here is a better practice: create a function that will return 1 if it is prime, and 0 if it is not. if you realize that it is a composite number, you should return immediately. if you get to the end of the loop, it is definatley a prime number. also, you can run your loop to the square root of n to gain a smaller amount of iterations, and not until n. good luck

    int isPrime(int n)
    {
        int i;
        for (i = 2; i < (int) sqrt(n) ; i++)
        {
            if (n % i == 0)
            {
                printf("number is composite");
                return 0;
            }
        }
        printf("number is prime");
        return 1;
    }
Chaos Monkey
  • 964
  • 1
  • 6
  • 18
0

Here you are.

#include <stdio.h>

int main( void )
{
    while ( 1 )
    {
        unsigned int n = 0;
        _Bool prime;

        printf( "\nEnter a non-negative number (0-exit): " );
        scanf( "%u", &n );

        if ( !n ) break;

        prime = n == 2 || ( n % 2 && n != 1 );

        for ( unsigned i = 3; prime && i * i <= n; i += 2 )
        {
            prime = n % i;
        }            

        printf( "Number %u is %s\n", n, prime ? "prime" : "composite" );
    }

    return 0;
}

If to enter sequentially

1 2 3 4 5 6 7 8 9 0

then the output is

Enter a non-negative number (0-exit): 1
Number 1 is composite

Enter a non-negative number (0-exit): 2
Number 2 is prime

Enter a non-negative number (0-exit): 3
Number 3 is prime

Enter a non-negative number (0-exit): 4
Number 4 is composite

Enter a non-negative number (0-exit): 5
Number 5 is prime

Enter a non-negative number (0-exit): 6
Number 6 is composite

Enter a non-negative number (0-exit): 7
Number 7 is prime

Enter a non-negative number (0-exit): 8
Number 8 is composite

Enter a non-negative number (0-exit): 9
Number 9 is composite

Enter a non-negative number (0-exit): 0
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Another approach to find whether a number is prime or not can be :-`

#include<stdio.h>

void main()
{
    int no,i;
    char x='y';
    printf("Enter a number : ");
    scanf("%d",&no);

 for (i=2;i<=no/i;i++)
     {
       if(no%i==0)
       {
          x='n';
          break;
       }
     }
 if(x=='y')
    printf("The number is a prime number. ");
 else
    printf("The number is not prime number. ");
}

The logic here is to limit the number of test cases to (the quotient of the number being tested and the value of the loop counter) since a divisor cannot exceed this quotient.