List of all available Websheets
Viewing java/07-recursion/Factorial by daveagp@gmail.com. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
Property | Value |
---|---|
Description html markup shown to student | Write a recursive method <code>factorial(n)</code> that returns n × (n-1) × (n-2) × … × 3 × 2 × 1. For example, <code>factorial(4)</code> should return 24 since that is the value of 1 × 2 × 3 × 4. |
Public permissions | |
Engine | |
Template / Reference solution | public static \[long]\ factorial(\[int n]\) { // base case if (\[n == 0]\) return \[1]\; // reduction step // note that n! = n * (n-1) * ... * 2 * 1 = n * ((n-1) * ... * 2 * 1) return \[n]\ * factorial(\[n-1]\); } public static void main(String[] args) { StdOut.println(factorial(4)); // should be 24 StdOut.println(factorial(10)); // should be 3628800 StdOut.println(factorial(20)); // watch for overflow. what return type? } |
Java test suite See manual | testMain(); test("factorial", 1); test("factorial", 6); test("factorial", 11); |
Solution visibility |
Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.