Not logged in. Log in with GitHub. About Websheets.

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.
PropertyValue
Description
html markup
shown to student
 
Write a recursive method <code>factorial(n)</code>
that returns n &times; (n-1) &times; (n-2) &times; &hellip; &times; 3 &times; 2 &times 1. For example, <code>factorial(4)</code> should return 24 since that is the value of 4 &times; 3 &times; 2 &times; 1.
Public permissions remove
Engine
Template / Reference solution
 
#include <iostream>
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 remove


Optional properties:

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'.