Created
July 14, 2022 19:06
-
-
Save alwaisy/30192f662733f3b0dd23cb8691ccde48 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// problem | |
Objective | |
Today, we are learning about an algorithmic concept called recursion. Check out the Tutorial tab for learning materials and an instructional video. | |
Recursive Method for Calculating Factorial | |
Function Description | |
Complete the factorial function in the editor below. Be sure to use recursion. | |
factorial has the following paramter: | |
int n: an integer | |
Returns | |
int: the factorial of | |
Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of . | |
Input Format | |
A single integer, (the argument to pass to factorial). | |
Constraints | |
Your submission must contain a recursive function named factorial. | |
Sample Input | |
3 | |
Sample Output | |
6 | |
Explanation | |
Consider the following steps. After the recursive calls from step 1 to 3, results are accumulated from step 3 to 1. | |
// solution => all tests are passed | |
'use strict'; | |
const fs = require('fs'); | |
process.stdin.resume(); | |
process.stdin.setEncoding('utf-8'); | |
let inputString = ''; | |
let currentLine = 0; | |
process.stdin.on('data', function(inputStdin) { | |
inputString += inputStdin; | |
}); | |
process.stdin.on('end', function() { | |
inputString = inputString.split('\n'); | |
main(); | |
}); | |
function readLine() { | |
return inputString[currentLine++]; | |
} | |
/* | |
* Complete the 'factorial' function below. | |
* | |
* The function is expected to return an INTEGER. | |
* The function accepts INTEGER n as parameter. | |
*/ | |
function factorial(n) { | |
// Write your code here | |
if (n <= 1) { | |
return 1 | |
} | |
else{ | |
const result = n * factorial(n - 1) | |
return result | |
} | |
} | |
function main() { | |
const ws = fs.createWriteStream(process.env.OUTPUT_PATH); | |
const n = parseInt(readLine().trim(), 10); | |
const result = factorial(n); | |
ws.write(result + '\n'); | |
ws.end(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment