Write a program that takes as input two positive integers A and B, then calls a recursive function that finds the product of A by B using the Egyptian method. The Egyptian method rules are:

  • If B=0 then A*B=0
  • If B is even then A*B = (2*A) * (B/2)
  • If B is odd then A*B = A * (B-1) + A

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

int mult(int A, int B)
{
    if(!B) return 0;
    if(!B%2) return mult(2*A,B/2);
    return mult(A , B-1) + A;
}

int main()
{
    int A, B;
    do
    {
        printf("Enter A > 0: ");
        scanf("%d",&A);
    }while(A<=0);
    
    do
    {
        printf("Enter B > 0: ");
        scanf("%d",&B);
    }while(B<=0);
	
    printf("%d * %d = %d\n",A,B,mult(A,B));
    return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
N-ary tree