.

...

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

unsigned martian( unsigned a, unsigned b )
{
   if ( b == 1 ) return a;
   return ( b % 2 ? a : 0 ) + martian( a + a, b / 2 );
}

int main()
{
   unsigned a, b;
   cout << "Enter two numbers: ";   cin >> a >> b;
   cout << martian( a, b ) << '\n';
}
Your code isn't standard c++ - System.out.println("Z: " + z); ???

Are you using C++/cli ?
The method as described doesn't work for 6 * 7:

6 7

12 3
24 1

ans = 12 + 24 = 36 -> wrong!

[NB lastchance's code does produce the correct answer!]

But does work for 7 * 6:
7 6

14 3
28 1

ans = 14 + 28 = 42 -> correct
ans = 12 + 24 = 36 -> wrong!

I think you do have to include the first line (because 7 is an odd number):
ans = 6 + 12 + 24 = 42 -> correct!


The reason that doesn't matter for 7*6 is that 6 is even, so 7 wouldn't be included in the sum.


I have to admit that the question statement seems over-complicated.


The OP's code looks like Java, but I've now forgotten all the Java I once learnt. C++ is far better.
Last edited on
As an iterative way, possibly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

unsigned martian(unsigned a, unsigned b)
{
	unsigned res {};

	for (; b >= 1; b >>= 1, a <<= 1)
		if (b % 2)
			res += a;

	return res;
}

int main() {
	unsigned a{}, b{};

	std::cout << "Enter two numbers: ";
	std::cin >> a >> b;
	std::cout << martian(a, b) << '\n';
}

Last edited on
Well, everywhere else seems to call this the "Russian Peasant Method of Multiplication" (let's not even go there!):
https://www.wikihow.com/Multiply-Using-the-Russian-Peasant-Method

Wonder how the martians got their hands on it.
Topic archived. No new replies allowed.