HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Binary Multiplication in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
binarymultiplicationstackoverflow

Problem

Question:Write an algorithm in C to do integer multiplication without using multiplication nor division operators.

Could I get a critique of the doMultiplication function? I know the rest of the code has some dumb stuff in it (like using scanf), but I'm looking for feedback on my multiplication implementation. Are there any cases it won't handle? Is there anything I could possibly have done to optimize it? And lastly, is there anything that would make it more readable?

#include 
#include 
/*
Write an algorithm/code in C to do integer multiplication  without using multiplication nor division operators. 
 */
void main()
{
  int n;
  int m;
  int result;
  printf("Please enter numbers to multiplye\n");  
  printf("First number\n");  
  int multiple1 = getNumberFromUser();
  printf("\nSecond number\n");
  int multiple2 = getNumberFromUser();
  result = doMultiplication(multiple1,multiple2);
  printf("Result of multiplication = %d\n", result);
}

int getNumberFromUser()
{
  char arg1[10]; 
  int retry = 0;
  int multiple;
  while(retry == 0)
  { 
    printf("Please enter a number:");
    scanf("%s", arg1);
    if(isNumericInput(arg1) != 0)
    {
      char * strEnd;
      multiple = strtol(arg1,&strEnd, 10);
      retry = 1;
    } else {
      printf("Bzzz wrong answer genius try a number \n");
    }
  }

  return multiple;

}

int isNumericInput(char arg[]){
  char * strEnd;
  int userInput = strtol(arg, &strEnd, 10);
  return userInput;
}

int doMultiplication(int n, int m)
{
  int result = 0;
  while(m != 0)
  {
    if((m & 1) != 0)
    {
      result = result + n;
    }
    n = n > 1;
  }
  return result;
}

Solution

Basically your algorithm looks correct, however:

  • You should use unsigned ints or have some treatment for the signs, otherwise I guess (didn't check it though) that your results for negative numbers will be wrong



  • Don't test for 0 explicitly, i.e. just write while(m) and if(m & 1)

Context

StackExchange Code Review Q#10006, answer score: 4

Revisions (0)

No revisions yet.