Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C / C++ Interview: Code Optimization

I had an interview today. This question was to optimize the code below. if we will see the code below after for loop there are four steps of "if-else" follows. So, interviewer asked me optimize it to 3 if-else line. I have tried a lot. But could not able to find the solution. Even he told me if you know scripting language then, you can use them also. Please help me in optimizing the same.

int main()
{
    int i = 1;
    for(i; i <= 100; i++)
    {
        if((i % 3 == 0 && i % 5 == 0))
        {cout << "PR\n";}
        else if(i % 3 == 0)
        {cout << "P\n";}
        else if(i % 5 == 0)
        {cout << "R\n";}
        else
        {cout << i <<"\n";}
    }
system("pause");
return 0;
}
like image 587
Rasmi Ranjan Nayak Avatar asked Nov 01 '25 14:11

Rasmi Ranjan Nayak


1 Answers

This is a well known question... the "FizzBuzz".

You can even solve it without any explicit IFs

const char *messages[] = {"%i\n", "P\n", "R\n", "PR\n"};

for (i=1; i<=100; i++) {
    printf(messages[((i % 3)==0) + 2*((i % 5)==0))], i);
}
like image 54
6502 Avatar answered Nov 03 '25 22:11

6502



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!