recursive memoization streamlining

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 :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
/*
 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>

static unsigned long int a[1000000] = {0};

int converter (int coin);

int main(int argc, const char * 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;
    }
    else if (a[coin] != 0)
    {
        return a[coin];
    }
    else if(coin >= sum)
    {
        return coin;
    }
    else if (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
Last edited on
Topic archived. No new replies allowed.