Quote:Original post by ahung89
you guys are going to hate me, but after hours of trying I asked my dad who is a computer science/math major to help me and he figured it out in less than 30 seconds...
i just had to make it so that if n = 0 it draws a star, then call the function with n-1 twice... wow i feel stupid. I'm trying right now to fully understand how it works. He drew a tree similar to the one EAX did. I can see now why it works, I don't know how the hell he figured that out so fast. Exponents just confuse the hell out of me. Oh well, all part of learning I guess.
If you focus too hard on the exponent you'll overthink the problem. The way I figured it out was to draw the the results on a piece of paper first:
0 = *
1 = **
2 = ****
3 = ********
Then, looking at it (forgetting about exponents), you can see that each increasing value just prints out twice as many stars than the previous value:
0 = *
1 = *,* // twice "0"
2 = **,** // twice "1"
3 = ****,**** // twice "2"
The only one that isn't "twice" the previous, is 0. So, I knew that the first thing my function should check for is n == 0:
void printStars(int n){ if(n == 0) { cout << "*"; return; }}
Then, looking at "1", I realize that I just need to do "0" twice. And if I get "2", I just need to do "1" twice, and if I get "3", do "2" twice, and so and on. The common pattern here? Just do the previous value twice, and print a star if you get zero.
void printStars(int n){ if(n == 0) { cout << "*"; return; } printStars(n - 1); printStars(n - 1);}
The point is - this was all figured out without me really focusing on the 2^n part, and chances are neither did your dad.
Problems like these are good ones - you learn to focus on the problem itself and ignore the parts that make it sound more complicated than it is.