Is There a Method That Calculates a Factorial in Java

Is there a method that calculates a factorial in Java?

I don't think it would be useful to have a library function for factorial. There is a good deal of research into efficient factorial implementations. Here is a handful of implementations.

Display whole calculation for getting a factorial of a number (java)

public static String calculateFactorialStr(int val) {
String res = IntStream.range(0, val)
.map(i -> val - i)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" * "));
return res + " = " + calculateFactorial(val);
}

public static long calculateFactorial(int val) {
long res = 1;

for (int i = 2; i <= val; i++)
res *= i;

return res;
}

Calculate the Factorial of userinput

Code which is use to calculate factorial given input number from the user:

import java.util.Scanner;

class Factorial
{
public static void main(String args[])
{
int n, c, fact = 1;

System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);

n = in.nextInt();

if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;

System.out.println("Factorial of "+n+" is = "+fact);
}
}
}

OR
In more modular way

import java.util.Scanner;

public class Factorial {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println("The factorial of " + n + " is " + result);
}

public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
}

Calculating factorials with numbers bigger than ints and longs in java?

You can use BigInteger in java, it has as much numbers as you want

    BigInteger fact= BigInteger.ONE;
int factorialNo = 10;

for (int i = 2; i <= factorialNo; i++){
fact = fact.multiply(new BigInteger(String.valueOf(i)));
}

System.out.println("The factorial of " + factorialNo +
" (or " + factorialNo + "!) is: " + fact);
final int digits = fact.toString().length();

BigInteger number = new BigInteger(fact.toString());
BigInteger reminder;
BigInteger sum = BigInteger.ZERO;
BigInteger ten = new BigInteger(String.valueOf(10));

while(number.compareTo(BigInteger.ONE)>=0)
{
reminder=number.mod(ten);
sum=sum.add(reminder);
number=number.divide(ten);
}

System.out.println("The total sum of all the " + digits
+ " idividual digits from the answer of the factorial of "
+ factorialNo + " is: " + sum

EDIT: the code is improved to be compatible with author's code

factorial method doesn't work well!

Since 500! equals 1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 you can't fit it into an int (which ranges up to 2147483647).

  • Using an int you can only store up to 12!.
  • Using a long you'll get up to 20!
  • Using a double you'll get up to 170!.
  • By convention 0! equals 1;

Here is a solution using BigInteger:

public static BigInteger factorial(int i) {
if (i == 0) {
return BigInteger.ONE;
}
BigInteger n = BigInteger.valueOf(i);
while (--i > 0) {
n = n.multiply(BigInteger.valueOf(i));
}
return n;
}

Factorial Java Program

Try

public static void main(String[] args) {
int num;
int fact=1;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
num = input.nextInt();
for (int i=2;i<=num; i++){
fact=fact*i;
}

System.out.println("Factorial: "+fact);
}

As @Marko Topolnik mentioned in comments this code will work for inputs up to 12. For larger inputs will output infinity due to overflow.

For numbers larger than 12 you should use higher data type like BigInteger

You can try:

public static void main(String[] args) {
BigInteger num;
BigInteger fact = BigInteger.valueOf(1);
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
num = input.nextBigInteger();
for (int i = 2; i <= num; i++){
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println(fact);
}

Calculating factorials in Java and printing the steps

That is happening because you're printing the factorial variable only. Replace:

System.out.println(factorial + " * " + n + " = " + factorial);

with:

System.out.println(factorial + " * " + n + " = " + factorial * n);

calculate factorial recursive in functional style Java

There are twice as many calls in the functional style as compared to function calls. see image.

Functional Style - double stacks

Function invocation - single stacks

So while the stack size increases to 11,111 calls in latter, it increases by over 22,222 calls in functional style. I believe stack limit in your environment should be between 11111 and 22222 so that explains why it breaks. So in this sense Functional style seems inefficient.

You can increase the stack size using -Xss described in the below link.

Or, better to use tail recursion which looks something like this:

private static BiFunction<BigInteger, BigInteger, BigInteger> factorialTR = (n, acc) -> BigInteger.ONE.equals(x)
? BigInteger.ONE
: Main.factorialTR.apply(x.subtract(BigInteger.ONE), acc * n));

This will still cause StackoverflowError in Java as it does not support tail call optimization. But Scala, lisp do, there you wont get one.

Refs

  • Tail-recursive factorial
  • Leetcode explanation(requires login)
  • max stack depth

calculating factorial using Java 8 IntStream?

You can use IntStream::reduce for this job,

int number = 5;
IntStream.rangeClosed(2, number).reduce(1, (x, y) -> x * y)


Related Topics



Leave a reply



Submit