Home > front end >  Why doesn't my code work for special cases?
Why doesn't my code work for special cases?

Time:12-24

I wrote up a piece of code to find whether a number is prime or not and here it is.

#include <stdio.h>
void main(){
    int i,n;
    printf("Enter value for n: ");
    scanf("%d", &n);
    if (n <= 3){
        printf("It is a prime number");
    }
    for (i = 2; i < n; i  ){
        if (n % i == 0){
            printf("It's not prime number \n");
            break;
        } else {
            printf("It is a prime number \n");
            break;
        }
    }
}

However, when my input is 33, instead of the output printing "It's not a prime number", since 33 is divisible by 3 and 11, it prints that "It is a prime number".

What is the problem with my code here?

CodePudding user response:

You almost got it right: you just have to make sure the program exits after having established whether a number is prime.

Also, you can stop the loop at n/2.

Last, but not least: main should return a int.

#include <stdio.h>
int main(void){
    int i,n;

    printf("Enter value for n: \n");
    scanf("%d", &n);
    if (n <= 3){
        printf("It is a prime number\n");
        return 0;
    }
    for (i = 2; i < n/2; i  ){
        if (n % i == 0){
            printf("It's not prime number \n");
            return 0;
        }
    }    
    printf("It is a prime number \n");
    return 0;
}

CodePudding user response:

You might want to try this:

#include <bits/stdc  .h>
    int main(){
        int i,n;
        printf("Enter value for n: ");
        scanf("%d", &n);
        if (n <= 1){
            printf("It is a prime number");
        }
        for (i = 2; i <= sqrt(n); i  ){
            if (n % i == 0){
                printf("It's not prime number \n");
                return 0;
            } 
            }
        printf("A prime Number");
        return 0;
    }  

This is happening because in your code, for i = 3, and n = 33 if condition is failing which leads to else block directly and hence you are getting output as "It is a prime number"

CodePudding user response:

In your code, the first time the for loop is executed it immediately triggers either the if condition or else, then breaks, reaches the end and returns. The loop runs a total of 1 iteration max. Change to the following:

for (i = 2; i*i < n; i  ){
    if (n % i == 0){
        printf("It's not prime number \n");
        return 0;
    }
}
printf("It is a prime number \n");

Here the for runs correctly. It checks for all dividends, only then it's over and prints the false condition. Note you can optimize your code and only check up to the square root of n, because after that it can't hit true.

And add a return statement here, because the program is already over and doesn't need to continue:

if (n <= 3){
    printf("It is a prime number");
    return 0;
}
  • Related