I want to know what is causing wrong answer in my code

Link for the question: Contest Page | CodeChef
Here’s my answer

#include <stdio.h>

int main(void) {
int t, num;
scanf("%d", &t);
while(t--)
{
    int counter = 0;
    scanf("%d", &num);
    if(num > 1)
    {
	    for(int i = 2 ; i <= num/2 ; i++)
	    {
	        if(num % i == 0)
	        {
	            counter = 1;
	        }
	    }
	    if(counter == 1) printf("no\n");
	    else printf("yes\n");
    }
}
return 0;
}

Please guide me as I am a beginner.

What happens if N=1?

1 Like

Hi

I realized that my code was not there. I’m sorry for the inconvenience. Now I’ve edited my question. Can you please look into my code and suggest what’s giving wrong answer.

1 Like

Well you have put the whole output statements under a single if(Num>1) so if Num<=1 your program won’t output anything. Anyways it’ll be better if you posted the question also.
I feel this should run now.


int main(void) {
int t, num;
scanf("%d", &t);
while(t--)
{
    int counter = 0;
    scanf("%d", &num);
    if(num > 1)
    {
	    for(int i = 2 ; i <= num/2 ; i++)
	    {
	        if(num % i == 0)
	        {
	            counter = 1;
	        }
	    }
    }
if(counter == 1) printf("no\n");
else printf("yes\n");
}
return 0;
}
1 Like

Hi

I tried that, but still, it gave me the wrong answer. I added separately if block for checking primality of num <= 1 as shown below, but wrong answer again popped up.

#include <stdio.h>

int main(void) {
int t, num;
scanf("%d", &t);
while(t--)
{
int counter = 0;
scanf("%d", &num);
if(num > 1)
{
    for(int i = 2 ; i <= num/2 ; i++)
    {
        if(num % i == 0)
        {
            counter = 1;
        }
    }
}
if(num <= 1) printf("no");
else{
    if(counter == 1) printf("no\n");
	else printf("yes\n");
}
}
return 0;
}

I tried adding a break statement after counter = 1 assignment, still, it was giving the wrong answer.

Consider the test input:

5
1
1
2
1
1
2 Likes

It would be better if you posted the question also.

1 Like

I’m assuming you’re running a code with test cases which checks if for each test case a number is prime or not.

You can use this method and call in each test case:

int checkPrime(int n){
   if(n<=1) return 0;
   int L=(int)sqrt(n);
   for(int i=2;i<=L;i++){
      if(n%i==0) return 0;
   }
   return 1;
}
1 Like

Thank you all for helping me. I simply had to put a line break after printing “no” for num <= 1. I’ll take care of these silly errors next time. Thanks for your precious time :relieved:

1 Like