Tried two approach for the problem below:
You are asked to calculate factorials of some small positive integers.
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
For each integer n given at input, display a line with the value of n!
Time limit 2 sec(s)
Memory limit 256 MB
Source limit 1024 KB
(http://www.hackerearth.com/problem/small-factorials/)
/*Without recurrsion*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class factorial {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int arr[] = new int[t];
for (int i = 0; i < t; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
for(int i=0; i<t; i++){
BigInteger res= BigInteger.valueOf(1);
while(arr[i]>1){
res = res.multiply(BigInteger.valueOf(arr[i]--));
}
System.out.println(res);
}
}
}
Statistics:
| Result | Time (Sec) | Memory (KiB) |
| 100 | 3.3222 | 11790732 |
/*With recurrsion*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class recurrsion_fact {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int arr[] = new int[t];
for (int i = 0; i < t; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
for(int i=0; i<t; i++){
System.out.println(factorial(arr[i]));
}
}
private static BigInteger factorial(int num){
BigInteger res= BigInteger.valueOf(num);
if(num == 0){
return BigInteger.valueOf(1);
}
else{
res = res.multiply(factorial(--num));
}
return res;
}
}
Statistics:
| Result | Time (Sec) | Memory (KiB) |
| 100 | 2.4186 | 12053904 |
Recurrsion is a trade off between speed and memory useage. :)
No comments:
Post a Comment