-
challenge from The First Book of Java
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
-
easy.
And your problem is...?
-
no idea how to do this without the math class
-
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.
Last edited by nspils; 10-05-2006 at 08:41 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
Last edited by masher; 10-05-2006 at 09:37 PM.
Similar Threads
-
Replies: 2
Last Post: 06-14-2006, 03:16 PM
-
Replies: 3
Last Post: 05-03-2006, 12:32 PM
-
Replies: 1
Last Post: 05-13-2005, 06:46 AM
-
By Mike Tsakiris in forum .NET
Replies: 11
Last Post: 10-04-2002, 05:32 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks