Factorial: Difference between revisions

Content added Content deleted
(added Fortran)
(Added Java, sample output doesn't need to be tabbed since it's labelled)
Line 2: Line 2:


Write a function to return the factorial of a number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). Support for trapping negative n errors is optional.
Write a function to return the factorial of a number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). Support for trapping negative n errors is optional.

==References==
[http://en.wikipedia.org/wiki/Factorial Wikipedia]


=={{header|Ada}}==
=={{header|Ada}}==
Line 93: Line 90:
nfactorial = PRODUCT((/(i, i=1,n)/))
nfactorial = PRODUCT((/(i, i=1,n)/))


=={{header|Java}}==

===Iterartive===
<java>public static long fact(int n){
if(n < 0){
System.err.println("No negative numbers");
return 0;
}
long ans = 1;
for(int i = 1;i < n;i++){
ans *= i;
}
return ans;
}</java>
===Recursive===
<java>public static long fact(int n){
if(n < 0){
System.err.println("No negative numbers");
return 0;
}
if(n == 0) return 1;
return n * fact(n-1);
}</java>
=={{header|Python}}==
=={{header|Python}}==
===Iterative===
===Iterative===
Line 112: Line 130:
</python>
</python>


:Sample output:
Sample output:


:<python>
<python>
: >>> for i in range(6):
>>> for i in range(6):
: print i, factorial(i)
print i, factorial(i)
:
: 0 1
0 1
: 1 1
1 1
: 2 2
2 2
: 3 6
3 6
: 4 24
4 24
: 5 120
5 120
: >>>
>>>
:</python>
</python>


===Numerical Approximation===
===Numerical Approximation===