To multiply two integers X and Y, repeat the following double operation on the pair (X, Y), as long as Y is different from 0: multiply X by 2 and divide Y by 2 (integer quotient). The result is equal to the sum of the multiples of X corresponding to quotients of Y odd (including the initial pair).

Example: X=7  and Y=9, answer = 0

  • Y is different from 0, Y is odd, answer = x = 7
  • Y is different from 0, X = 14 , Y = 4,  Y is even, answer remains 7
  • Y is different from 0, X = 28 , Y = 2,  Y is even, answer remains 7
  • Y is different from 0, X = 56 , Y = 1,  Y is odd, answer = 7+X=7 + 56 = 63 
  • Y is different from 0, X = 112 , Y = 0,  Y is even, answer remains 63
  • Y is equal to 0, answer = 63 

write the function mult which implements this multiplication algorithm.


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>

int mult(int X, int Y)
{
	int S=0;
 	do { 
    		if (Y%2!=0) 
			S=S+X;
    		X=X*2;              
    		Y=Y/2;
  	} while (Y!=0);
	return S;
}
void main()  
{
  	int a,b;
  	printf("Enter 2 integers: ");
  	scanf("%d%d",&a,&b);

  	printf("%d times %d = %d\n",a,b,mult(a,b));
	getch();
}

 

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Binary tree rotations