I'm new to memoization and was working on this problem and the code seems to execute well and rather quickly. I was just looking for some input on if this is the proper way to be solving the problem and if something should be done to make it any faster? Thanks :)
/*
n Byteland they have a very strange monetary system.
Each Bytelandian gold coin has an integer number written on it. A coin n can
be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers
are all rounded down (the banks have to make a profit).
You can also sell Bytelandian coins for American dollars. The exchange rate is
1:1. But you can not buy Bytelandian coins.
You have one gold coin. What is the maximum amount of American dollars you can
get for it?
*/
#include <iostream>
staticunsignedlongint a[1000000] = {0};
int converter (int coin);
int main(int argc, constchar * argv[]) {
int coin(0), dollars(0);
//coin is less than one million
std::cout << "Enter a coin to see how many american dollars you can get: ";
std::cin >> coin;
dollars = converter(coin);
std::cout << "Your " << coin << " coin is worth " << dollars << " dollars\n";
return 0;
}
int converter (int coin)
{
int sum = coin/2 + coin/3 + coin/4;
if (coin < 12)
{
return coin;
}
elseif (a[coin] != 0)
{
return a[coin];
}
elseif(coin >= sum)
{
return coin;
}
elseif (coin < sum)
{
a[coin] = converter(coin/2) + converter(coin/3) +converter(coin/4);
}
return a[coin];
}
like for example I tried moving the summing later but then the program got mad over the else ifs which I didn't fully understand it said something about missing expression