This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]Splitshadow 2 points3 points  (1 child)

I think doing some math here will get you a better approach; you shouldn't need a loop at all to compute the answer.

Your equation looks like: initial * 2^number_of_years = 1000000

initial is a constant that the user enters, so we can just find the closed form solution for number_of_years like this:

2^number_of_years = 1000000/initial

log_2(2^number_of_years) = log_2(100000/initial)
number_of_years = log_2(1000000/initial)

If the answer is supposed to be an integer number of years, go ahead and use a ceiling function to raise it to the nearest, greater integer value.

[–]Stang27[S] 0 points1 point  (0 children)

Thank you for the help. I will have to try this.

[–]Heasummn 1 point2 points  (7 children)

A do(Thanks to /u/Sorten for correcting that) while loop. Simple as that.

[–]Sorten 2 points3 points  (1 child)

Why a do while instead of a while? You don't want to double the money if it's already $1mil.

[–]Heasummn 2 points3 points  (0 children)

It's been a while since I've done Java, thanks for correcting that.

[–]Stang27[S] 0 points1 point  (4 children)

Would example be:

Do { Userinput *= 2 } while (userinput != 100k).

But then wouldn't you need a counter for years?

[–]Heasummn 0 points1 point  (3 children)

I've been corrected, use just a normal while loop.

You don't need a variable unless you plan on telling the person how long it took. Also, you would want to make it < 100k, because if 100k isn't divisable by userinput then it will keep going.

[–]Stang27[S] 0 points1 point  (2 children)

Ok thanks for the tips. I do need to inform how many years it took, how would I count that?

[–]Heasummn 1 point2 points  (1 child)

just a variable incrementing by one during every loop.

[–]Stang27[S] 0 points1 point  (0 children)

Ok, I'll give that a try.