Click to See Complete Forum and Search --> : challenge from The First Book of Java


Rich jerk
10-05-2006, 03:05 AM
1)Prompt the user and accept a number from standard input.
2)Prompt the user and accept a symbol character from standard input. The symbol must be either an ^ or an !. If it is neither of these, display an error message and end the program.
3)If the symbol is a !, compute the factorial of the number entered in step 1 and display the result.
4) if the symbol is a ^, prompt the user to enter a second number, and then calculate the 1st number to the power of the 2nd number (similar to tonight's exercise). Display the result.
5) You must use iteration/loops for the factorial and exponent calculations

can't use math class

masher
10-05-2006, 07:13 PM
easy.

And your problem is...?

Rich jerk
10-05-2006, 08:02 PM
no idea how to do this without the math class

nspils
10-05-2006, 08:39 PM
Given n, factorial is the result of multiplying the numbers 1 to n ... so you can create a for loop which counts up to n, multiplying "current result" by the current value of your counter

Given x to the power of y, you multiply x by itself y times. Make sure to test for the special cases of y being 0, y being 1; if not a special case then counting from 2 to y, with the new result in each iteration being current result times x.

You CAN write each of these as a recursive algorithm.

masher
10-05-2006, 09:35 PM
I did them as a loop; not much experience with recursion, but i have done similar things before.


.


4! = 1 * 2 * 3 * 4
You can loop that.

You can also use recursion:
4! = 3! * 4


For powers:
2^4 = 2 * 2 * 2 * 2
x^0 = 1