List of all available Websheets
Viewing cpp/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 4 × 3 × 2 × 1. |
Public permissions | |
Engine | |
Template / Reference solution |
using namespace std; \[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]\); } int main() { int n; cin >> n; cout << factorial(n); } |
C++ test suite json list of stdin/args tests e.g. [{"stdin":"hi", "args":["4", "5"]}, {"stdin":"noargs"}] to just run once with no input use [{}] | [ {"stdin": "4"}, {"stdin": "1"}, {"stdin": "5"}, {"stdin": "6"}, {"stdin": "10"}, {"stdin": "20"} ] |
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'.