Task:
Complete the factorial function in the editor below. Be sure to use recursion.
factorial has the following paramter:
- int n: an integer
Solution:
1)Javascript:
'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
return n==1?1:n*factorial(n-1);
}
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();
}
2)Java:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'factorial' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER n as parameter.
*/
public static int factorial(int n) {
// Write your code here
if(n==1)return 1;
return n*factorial(n-1);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
int result = Result.factorial(n);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}