Different verdict for similar codes || CHEFWM

Failed on 1st and last task: Solution: 56105714 | CodeChef
AC Solution: Solution: 56106526 | CodeChef

Diff:
AC solution uses a break statement

for(int i = primes;i > 0;i--){
        if(n%i == 0){
            ans = i;
            break;
        }
    }
    cout << ans << "\n";

failed one using return

for(int i = primes;i > 0;i--){
        if(n%i == 0){
            cout << i << "\n";
            return;
        }
    }

Why does it fail if both are same logically?

Here’s what I understood from both the code:

Let’s take the test case n=10 m=1:
So, primes value for this test case will be 0.

Now in your AC solution:
As primes is 0 so the loop will never run, and output ans which was initialized before the loop as int ans=0 is printed 0 as print statement is out of loop.

For failed code:
Again, the value of primes is 0, the loop never runs, but this time we don’t print anything as the print statement is inside the loop and the loop never ran thus skipping an answer.

2 Likes

Your code with return statement is failing when the answer is 0. It prints no answer in that case. Run with the test case given in the problems statement.