C / C++ Interview: Code Optimization

3.4k views Asked by At

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;
}
5

There are 5 answers

2
6502 On BEST ANSWER

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);
}
3
Óscar López On

Here's one way, in Python:

for i in range(1, 101):
    s = ''
    if i % 3 == 0:
        s += 'P'
    if i % 5 == 0:
        s += 'R'
    if i % 3 != 0 and i % 5 != 0:
        s = i
    print(s)

Equivalently: using a flag, as shown in your own answer:

for i in range(1, 101):
    s, flag = '', False
    if i % 3 == 0:
        flag = True
        s += 'P'
    if i % 5 == 0:
        flag = True
        s += 'R'
    if not flag:
        s = i
    print(s)

Just for fun, a Python version of @6502's answer:

messages = ['{}', 'P', 'R', 'PR']
for i in range(1, 101):
    print(messages[(i%3 == 0) + 2*(i%5 == 0)].format(i))

And finally, my personal favorite (because it's the shortest) - using the Greatest Common Divisor function and a lookup table:

from fractions import gcd
messages = {3:'P', 5:'R', 15:'PR'}
for i in range(1, 101):
    print(messages.get(gcd(i, 15), i))
1
Rasmi Ranjan Nayak On

I found a solution. Please let me know whether it is good or not?

int main()
{
    int i = 1;int stat=0;
    for(i; i <= 100; i++)
    {
        stat=0;
        if(i%3 == 0){stat++; cout << "P";}
        if(i%5 == 0){stat++; cout << "R";}
        if(stat == 0)cout << i;
        cout << "\n";
    }
system("pause");
return 0;
}
0
Dima On

I really like 6502's answer, but here is a simple solution without extra variables:

for(i = 1; i <= 100; i++)
{
    if(i % 3 != 0 && i % 5 != 0)
    {
        printf("%d\n", i);
        continue;
    }

    if(i % 3 == 0)
        printf("P");

    if(i % 5 == 0)
        printf("R");

    printf("\n");
}
1
Simeng Yue On

this way only use 3 if

#include <iostream>
using namespace std;

int main()
{
 for (int i = 0; i <= 100; ++i)
 {
   bool fizz = (i % 3) == 0;
   bool buzz = (i % 5) == 0;
   if (fizz)
    cout << "Fizz";
   if (buzz)
    cout << "Buzz";
    if (!fizz && !buzz)
     cout << i;
    cout << endl;
  }
  return 0;
}