Factorial: Difference between revisions
Content added Content deleted
Tag: Manual revert |
|||
Line 4,471: | Line 4,471: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
===Parallelized (fastest and most efficient)=== |
|||
<syntaxhighlight lang="java5"> |
|||
package programas; |
|||
import java.math.BigInteger; |
|||
import java.util.InputMismatchException; |
|||
import java.util.Scanner; |
|||
import java.util.stream.Stream; |
|||
public class IterativeFactorial { |
|||
public BigInteger factorial(BigInteger n) { |
|||
if ( n == null ) { |
|||
throw new IllegalArgumentException("The argument cannot be null"); |
|||
} |
|||
else if ( n.signum() == - 1 ) { |
|||
// negative |
|||
throw new IllegalArgumentException("Argument must be a non-negative integer"); |
|||
} |
|||
else { |
|||
BigInteger result = Stream.iterate(BigInteger.TWO, bi -> bi.compareTo(n) <= 0, bi -> bi.add(BigInteger.ONE)) |
|||
.parallel().reduce(BigInteger.ONE, BigInteger::multiply); |
|||
return result; |
|||
} |
|||
} |
|||
static long count(BigInteger k) { // Count all digits |
|||
double factor = Math.log(2) / Math.log(10); |
|||
int count = (int) (factor * k.bitLength() + 1); |
|||
if ( BigInteger.TEN.pow(count - 1).compareTo(k) > 0 ) { return count - 1; } |
|||
return count; |
|||
} |
|||
public static void main(String[] args) { |
|||
Scanner scanner = new Scanner(System.in); |
|||
BigInteger number, result; |
|||
boolean error = false; |
|||
System.out.println("FACTORIAL OF A NUMBER"); |
|||
do { |
|||
System.out.println("Enter a positive integer:"); |
|||
try { |
|||
number = scanner.nextBigInteger(); |
|||
final long startTime = System.currentTimeMillis(); |
|||
result = new IterativeFactorial().factorial(number); |
|||
final long endTime = System.currentTimeMillis(); |
|||
error = false; |
|||
System.out.println("Factorial of " + number + ": " + result); |
|||
System.out.println("Total execution time: " + (endTime - startTime)); |
|||
// System.out.println("Factorial of " + number + " has " + count(result) + " |
|||
// digits"); |
|||
} |
|||
catch ( InputMismatchException | IllegalArgumentException e ) { |
|||
error = true; |
|||
scanner.nextLine(); |
|||
} |
|||
} |
|||
while ( error ); |
|||
scanner.close(); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
===Iterative=== |
===Iterative=== |
||
<syntaxhighlight lang="java5"> |
<syntaxhighlight lang="java5"> |