0
\$\begingroup\$

I had written a code which is given in the following code 1,code1 & Driver program section of the post.

I have to ask which of the following code is more efficient and takes less time to execute on the C(GCC 4.9.2) compiler.

I had a little confusion in the following code which is multiplication of input1 *input1 which I might think will takes lot more time so Is there any way to optimize like using bitwise multiplication.

Code 1

int FindingMoves(int input1)
    {
        if(input1>0)
        {
               ++input1;
               input1 <<=1;
               ++input1;
               return input1*input1;

        }
        if(input1 == 0){return 8;}
       
    }

This is the first code which I had written using bitwise multiplication but fails to write a code to multiply two numbers(input1*input1).

Code 2

int FindingMoves(int input1)
    {
        if(input1>0)
        {
              
               return (2*(input1+1)+1)*(2*(input1+1)+1);

        }
        if(input1 == 0){return 8;}
       
    }

This is straight forward code which is a simpler version of above.

DriverProgram

int main() {
    int output = 0;
    int ip1;
    scanf("%d", &ip1);
    output = FindingMoves(ip1);
    printf("%d\n", output);
    return 0;
}

This is the driver program to above code snippets.

Help me here to write optimized and efficient code. Any mysteries will be welcome regarding macro or something.

\$\endgroup\$
3
  • \$\begingroup\$ "following code 1,code1 & Driver program" Did you mean "following Code 1 , Code 2 & Driver program" (1--> 2)? \$\endgroup\$ Commented Jul 17, 2017 at 14:48
  • \$\begingroup\$ Code 1 and Code 2 are broken, missing return value when input < 0. \$\endgroup\$ Commented Jul 17, 2017 at 14:50
  • \$\begingroup\$ Both approaches square a number using *. Title does not match body goals. \$\endgroup\$ Commented Jul 17, 2017 at 14:54

1 Answer 1

1
\$\begingroup\$

Negative input causes undefined behavior

If input1 is negative, your code reaches the end of function without returning a value. Either you should return something such as 0 in that case, or you should make the input type be unsigned.

Simplification using math

Your expression (2*(input1+1)+1) evaluates to 2*input1+3. So to minimize the work done, you could do:

if (input1 > 0) {
    input1 += input1 + 3;
    return input1 * input1;
}

This has two adds, one multiply, and zero shifts. This is one less shift than the code in "code1" and one less multiply than the code in "code2", so it should be faster than either of them.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.