/* ;First homework exercise: ;Based on the definitions below of count-change, cc, and next, ;draw a tree showing the tree recursive calls of cc ;in execution of (count-change 26). ;What would the difference be for the call (count-change 27)? ; submit this homework on paper. */ typedef long long bigint; bigint count_change(int n); bigint cc(int n, int largest_coin); int next(int c); /* (define (count-change n) ; return the number of different ways to make change of n cents. (cc n 50)) */ bigint count_change(int n) { return cc(n, 50); } /* (define (cc n largest-coin) ; return the number of different ways to make change of n cents ; using no coins larger in amount than largest-coin. (cond ((zero? n) 1) ((= largest-coin 1) 1) ((< n largest-coin) (cc n (next largest-coin))) (else (+ (cc n (next largest-coin)) (cc (- n largest-coin) largest-coin))) )) */ bigint cc(int n, int largest_coin) { if (n == 0) return 1; if (largest_coin == 1) return 1; if (n < largest_coin) return cc(n, next(largest_coin)); else return cc(n, next(largest_coin)) // no use of largest + cc(n-largest_coin, largest_coin); // at least one use of largest } /* (define (next coin) (cond ((= coin 50) 25) ((= coin 25) 10) ((= coin 10) 5) ((= coin 5) 1) (else (error "next: unrecognized coin" coin)) )) */ #include using namespace std; int next(int c) { switch(c) { case 50: return 25; case 25: return 10; case 10: return 5; case 5: return 1; default: cerr << "next: no next coin for " << c << endl; } return -1; // error } int main() { cout << 5 << " " << count_change(5) << endl; cout << 6 << " " << count_change(6) << endl; cout << 10 << " " << count_change(10) << endl; cout << 23 << " " << count_change(23) << endl; cout << 230 << " " << count_change(230) << endl; cout << 2304 << " " << count_change(2304) << endl; cout << 23045 << " " << count_change(23045) << endl; cout << 230456 << " " << count_change(230456) << endl; }