The challenge for this month’s Exercise is to write code that uses the Ethiopian Multiplication method. The process involves doubling and halving the factors, then eliminating and finally tallying the result.
For my solution I use only a single while loop. This loop both tallies the results and doubles/halves the values. As I worked on the code, I discovered that you don’t really need to maintain a two-column list, which would involve more storage, but you can eliminate even value results in the second column as they’re calculated.
Here is my solution:
2024_11-Exercise.c
#include <stdio.h> int main() { int a,b,total; /* gather input */ printf("First value: "); scanf("%d",&a); printf("Second value: "); scanf("%d",&b); /* do math */ printf("Traditional: %d * %d = %d\n",a,b,a*b); printf(" Ethiopian: %d * %d = ",a,b); total = 0; while(a>0) { total += a%2 ? b : 0; a>>=1; b<<=1; } printf("%d\n",total); return 0; }
Variable a
is the first value, the first column. Variable b
is the second. I’m unsure whether a specific order is necessary. I didn’t test Ethiopian Multiplication to see if swapping the numbers changes anything. (I don’t think it would.)
The while loop spins until the value of a
is zero or less. Variable total
calculates the result, accumulating values as they’re manipulated.
The ternary operator tests to see whether variable a
(the first column) is even:
a%2 ? b : 0
If so, zero is added to variable total
. Otherwise, the value of variable b
is added to total
.
Next, variable a
is halved: a>>=1
Then variable b
is doubled: b<<=1
When the loop terminates, the result is output. It’s matched with the result generated from using the *
operator.
Here’s a sample run:
First value: 22
Second value: 47
Traditional: 22 * 47 = 1034
Ethiopian: 22 * 47 = 1034
I hope that your solution met with success! Remember, it need not be identical to mine. In fact, I can think of several ways to perform this calculation. As long as it uses the Ethiopian methodology and calculates the same result, consider your solution valid and passing the challenge.
Thank you, In the ternary operator if the condition is true, the first expression is executed.
You wrote:
a%2 ? b : 0, if a is even so b should added to a total variable but in this condition, zero is added to the total. Why?
If I change the condition to (a % 2 == 0) ? b : 0; we have different results.
Are there any differences between a%2 ? b : 0 with (a % 2 == 0) ? b : 0; ?
For more explain:
#include
int main()
{
int a = 18, b = 44, total = 0, total2 = 0;
total += (a % 2 == 0) ? b : 0; //44
total2 += a % 2 ? b : 0; //0
a >>= 1;
b <<= 1;
printf("%d\n%d", total, total2);
}
If you change
a%2
to(a%2==0)
you inverse the results.So when
a
is equal to 22,a%2
is equal to zero, FALSE. The value zero is then added to variabletotal
.On the other hand, when
a
is equal to 22 and you use(a%2==0)
you get TRUE, becausea
is equal to zero. In this instance, the value ofb
is added to the total, which messes up the result.