Need Explanation in Java Recursion - java

This is my code, I need an explanation of how this code works result=fact(n-1)*n;.My expected answer was not same as the output.I think after the return the stack should executing resumed state,the first execution state is
n=2 and (2-1)*2=2, then n=3,(3-1)*3=6, then n=4,(4-1)*4=12, then n=5,(5-1)*5=20.
The final answer I expected is 20. How did I get 120? How is the stack working in this scenario?. Thanks in advance.
public class Factorial
{
int fact(int n)
{
int result;
if(n==1) return 1;
result=fact(n-1)*n;
System.out.println("value of n="+n);
System.out.println(result);
return result;
}
}
class TestFact
{
public static void main(String[] args)
{
Factorial ob=new Factorial();
System.out.println("Final="+ob.fact(5));
}
}
The output of the given program is
value of n=2
2
value of n=3
6
value of n=4
24
value of n=5
120
Final=120

You misunderstood the method of calculating the factorial.
The method is defined as below for every n >= 1:
Cases:
fat(1) = 1 (by definition)
fat(2) = 2 * fat(1) (result on item 1) = 2 * 1 = 2
fat(3) = 3 * fat(2) (result on item 2) = 3 * 2 = 6
fat(4) = 4 * fat(3) (result on item 3) = 4 * 6 = 24
fat(5) = 5 * fat(4) (result on item 4) = 5 * 24 = 120
The algorithm is correct. You just misunderstood how factorial is calculated.
Improved code for better outputting
public class Factorial{
int fact(int n) {
int result;
if(n==1) return 1;
result=fact(n-1)*n;
System.out.println("Fat(" + n + ")=" + result);
return result;
}
public static void main(String[] args){
Factorial fat = new Factorial();
System.out.println("Final=" + fat.fact(5));
}
}
Try it online!

Your assumption is completely wrong.
Results of fact() function is 1, 2, 6, 24. So to get final result you need to multiply 1*2*6*24=120.
See recursion

Related

What exactly happening in this program specifically in the return statement?

The actual operation is performed in the line return
return (num == 1 ? 1 : num * firstFactorial(num - 1 ) );
How we get 40320 for num 8?
public class Factorial {
public static int firstFactorial(int num) {
return (num == 1 ? 1 : num * firstFactorial(num - 1 ) );
}
public static void main(String[] args) {
System.out.println(firstFactorial(8));
}
}
There are multiple things happening in that return statement. One could rewrite the firstFactorial function like this:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
int decreased = num - 1;
int recursiveFactorial = firstFactorial(decreased);
int result = num * recursiveFactorial;
return result;
}
First of all this is using a technique called recursion. The function is calling itself with the number parameter decreased by one. You can think of it like this:
1. You call firstFactorial with value of 8
2. firstFactorial(8) calls itself with a value of 7
3. firstFactorial(7) calls itself with a value of 6
...
8. firstFactorial(2) calls itself with a value of 1
9. firstFactorial(1) returns 1 because of the if-statement
After calling itself the function multiplies the return value of the recursive call with its own parameter and returns it. So it will go on like this:
10. firstFactorial(2) multiplies 1 with 2 and returns 2
11. firstFactorial(3) multiplies 2 with 3 and returns 6
10. firstFactorial(4) multiplies 6 with 4 and returns 24
...
14. firstFactorial(8) multiplies 5040 with 8 and returns 40320 to you
All together this will calculate the faculty of the value like this: 8 * 7 * 6 * ... * 1
The rest is more or less coding style and syntactic sugar.
You don't need local variables and perform the call and the operations in one line:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
return num * firstFactorial(num -1);
}
Then there is the ternary conditional operator in java (<cond> ? <true statement> : <false statement>) which allows you to express the whole function body in one line:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
return (num == 1) ? 1 : (num * firstFactorial(num -1));
}

What is the logic of the recursion

Here is I have a factorial code using recursion.
class Factorial
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println(f.fact(Integer.parseInt(args[0])));
}
private int fact(int num)
{
int result;
if(num == 1)
return 1;
result = fact(num - 1) * num;
return result;
}
}
Now to run this program, I did this
D:\>java Factorial 3
Now according to the logic when it enters the fact function, where num = 3, so it will skip to
result = fact(num - 1) * num;
Here it will become
result = fact(3 - 1) * num;
i.e. result = fact(2) * num;
In this step, I am little confused Does it execute whole step i.e.
result = fact(num - 1) * num;
or just the fact(num - 1)
According to the logic, what it should do is call the fact function. So, the control of the program again reaches to the start of the fact function where num = 2. It will again skip to
result = fact(num - 1) * num;
So, it will become
result = fact(2 - 1) * num;
i.e. result = fact(1) * num;
Now again, it should call the fact function without executing the whole syntax & again reaches to the start of the fact method where num = 1. This time num == 1 will be matched & 1 will be returned. Now it will return to
result = fact(num - 1) * num;
So, it will become
result = fact(1 - 1) * num;
i.e. result = fact(0) * num;
Now what will happen next ?
Am I going right ? If not what will be the correction ?
I dont clearly understand the flow of this recursion program.
So, it will become
result = fact(1 - 1) * num;
Nope. For num = 2,
result = fact(num - 1) * num;
becomes
result = 1 * num; // i.e. 1 * 2
fact returns a value, which means the entire call has to be replace with that value.
Not sure why you would even think num changes at all. You have no num = ... in your code.
I added some trace into the program. Execute it and see the output. Should be easy to follow.
package snippet;
class Factorial {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println(f.fact(Integer.parseInt("5")));
}
private int fact(int num) {
int result;
if (num == 1)
return 1;
result = fact(num - 1) * num;
System.out.println("fact(" + num + ") = " + result + " = fact(" + (num - 1) + ") * " + num);
return result;
}
}
fact(2) = 2 = fact(1) * 2
fact(3) = 6 = fact(2) * 3
fact(4) = 24 = fact(3) * 4
fact(5) = 120 = fact(4) * 5
120
Your logic is right but you have made 3 basic errors.
if we take your example;
First you run the program
D:\>java Factorial 3
then you have your first mistake because according to the logic all "num" have to be replaced by "3". So you get:
result = fact(3 - 1) * 3;
ie:
result = fact(2)*3;
then we have the second mistake because according to the definition of fact(num),
fact(2) = fact(2-1)*2
so we actually have
result = (fact(2-1)*2)*3
which is evaluated in
result = (fact(1)*2)*3
and here stand the third mistake because again according to fact(num) definition : fact(1) = 1 and not fact(1) = fact(1-1)*1
so we finally have:
result = ((1)*2)*3
To be more explicit if you follow all call sequence in the debugger you 'll have something like this( I put between brackets the value of the variable):
private int fact(num{3})
{
int result;
if(num{3}== 1)
return 1;
result = fact(num{3} - 1) * num{3};
private int fact(num{3-1})
{
int result;
if(num{3-1}== 1)
result = fact(num{3-1} - 1) * num{3-1};
private int fact(num{3-1-1})
{
int result;
if(num{3-1-1}== 1)
return 1;
}
return result{1*{3-1}};
}
return result{{1*{3-1}}*3};
}
Unless we hit the stop condition:
fact(num) = fact(num - 1) * num;
Therefore:
fact(3) = fact(3 - 1) * 3;
Keeping in mind that fact(1) = 1 (from the if statement early in the fact() method):
fact(3) = fact(2) * 3;
fact(2) = fact(1) * 2;
fact(1) = 1;
Replacing each element:
fact(3) = 1 * 2 * 3;
The recursion is used to repeatedly dive deeper into the process until a stop condition is encountered - in this case when num = 1.
The call f.fact(3) is expanding through the following steps:
1. result = fact(3 - 1) * 3 = fact(2) * 3
2. result = (fact(2 - 1) * 2) * 3 = (fact(1) * 2) * 3
3. result = 1 * 2 * 3 because fact(1) returns 1.
Your implementation is correct, But it will never reach fact(1-1) * 1 state ,as you return from method at if(num == 1).
num variable is limited to scope of method parameter. So for every call to fact method num variable is assigned a new value (i.e. num-1) and which is limited to that parameter scope only. So when fact(num-1) returns , value of num will be the original value and not the num-1.
The flow of your example is like this
step 1. fact(3)*3; //calling the function with num value 3
step 2. fact(2)*2; //calling fact() method again with num=2
step 3. fact(1)*1; //now num == 1 will be matched & 1 will be returned.
i. e.,
1 * 1 = 1; //now, steps 2 and 1 will be performed respectively
step 2. 1 * 2 = 2;
step 1. 2 * 3 = 6;
So, the final answer will be 6
Note: In step 3, the value is returned, so it will not again call this result = fact(0) * num; //which you have mentioned in question.

How do I print the factorials of 0-30 on a table

public static void main(String[] args) {
int n = factorial(30);
int x = 0;
while (x <= 30) {
System.out.println(x + " " + n);
x = x + 1;
}
public static int factorial (int n) {
if (n == 0) {
return 1;
} else {
return n * factorial (n-1);
}
}
}
I'm trying to print out something like this:
0 1
1 1
2 2
3 6
4 24
...etc, up to 30 (30!)
What I'm getting instead is this:
0 (30!)
1 (30!)
...etc, up to 30
In words, I'm able to create the left column from 0 to 30 but I want to make it print the factorial of the numbers in the right hand column. With my code, it only prints the factorial of 30 in the right-hand column. I want it to print the factorials in order next to their corresponding number. How can I fix my code to do this?
This is pretty simple. Instead of defining a variable, you call the method with the updated x every time:
System.out.println(x + " " + factorial(x));
Note that your loop could be rewritten as a for loop, which is exactly what they're designed for:
for (int x = 0; x < 30; x++) {
System.out.println(x + " " + factorial(x));
}
Note a couple of things:
The x++. It's basically a short form of x = x + 1, though there are some caveats. See this question for more information about that.
x is defined in the loop (for (int x = ...) not before it
n is never defined or used. Rather than setting a variable that's only used once, I directly used the result of factorial(x).
Note: I'm actually pretty certain that an int will overflow when confronted with 30!. 265252859812191058636308480000000 is a pretty big number. It also overflows long, as it turns out. If you want to handle it properly, use BigInteger:
public BigInteger factorial(int n) {
if (n == 0) {
return BigInteger.ONE;
} else {
return new BigInteger(n) * factorial(n - 1);
}
}
Because of BigInteger#toString()'s magic, you don't have to change anything in main to make this work, though I still recommend following the advice above.
As #QPaysTaxes explains, the issue in your code was due to computing the final value and then printing it repeatedly rather than printing each step.
However, even that working approach suffers from a lack of efficiency - the result for 1 computes the results for 0 and 1, the result for 2 computes the results for 0, 1, and 2, the result for 3 computes the results for 0, 1, 2, and 3, and so on. Instead, print each step within the function itself:
import java.math.BigInteger;
public class Main
{
public static BigInteger factorial (int n) {
if (n == 0) {
System.out.println("0 1");
return BigInteger.ONE;
} else {
BigInteger x = BigInteger.valueOf(n).multiply(factorial(n - 1));
System.out.println(n + " " + x);
return x;
}
}
public static void main(String[] args)
{
factorial(30);
}
}
Of course, it would be faster and simpler to just multiply in the loop:
import java.math.BigInteger;
public class Main
{
public static void main(String[] args)
{
System.out.println("0 1");
BigInteger y = BigInteger.ONE;
for (int x = 1; x < 30; ++x) {
y = y.multiply(BigInteger.valueOf(x));
System.out.println(x + " " + y);
}
}
}
Just for fun, here's the efficient recursive solution in Python:
def f(n):
if not n:
print(0, 1)
return 1
else:
a = n*f(n-1)
print(n, a)
return a
_ = f(30)
And, better still, the iterative solution in Python:
r = 1
for i in range(31):
r *= i or 1
print(i, r)

Find the sum of the digits in the number 100! (My while loop would not stop)

I've been trying to solve Problem 20 in Project Euler:
n! means n (n 1) ... 3 * 2 * 1
For example, 10! = 10 * 9 ... 3 * 2 * 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
This is what I came up with so far. I already got the correct answer (which was 648) with this code, but I got a bit OC, because my code is an infinite loop. After the result became 0 inside the while loop, it just wouldn't stop. Can anybody help me fix this?
public static BigInteger problem20(int max){
BigInteger sum = BigInteger.valueOf(0);
BigInteger result = BigInteger.valueOf(1);
BigInteger currentNum = BigInteger.valueOf(0);
for(long i = 1; i<=max; i++){
result = result.multiply(BigInteger.valueOf(i));
//System.out.println(result);
}
while (!result.equals(0)) {
sum = sum.add(result.mod(BigInteger.valueOf(10)));
result = result.divide(BigInteger.valueOf(10));
System.out.println(sum + " "+ result);
}
return sum;
}
This is the problem:
while (!result.equals(0))
result is a BigInteger, which will never be equal to an Integer. Try using
while (!result.equals(BigInteger.ZERO))
Another possibility is to use while (fact.compareTo(BigInteger.ZERO) > 0).
I recommend you to use BigInteger.ZERO, BigInteger.ONE and BigInteger.TEN where it is possible.
Example:
import java.math.BigInteger;
public class P20 {
public static void main(String[] args) {
System.out.println(getSum(100));
}
private static long getSum(int n) {
BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
fact = fact.multiply(BigInteger.valueOf(i));
}
long sum = 0;
while (fact.compareTo(BigInteger.ZERO) > 0) {
sum += fact.mod(BigInteger.TEN).longValue();
fact = fact.divide(BigInteger.TEN);
}
return sum;
}
}
It takes 4 ms.
It can be improved using the following observation:
the sum is not influenced by zeros => you don't need to multiply by 10 and 100 and instead of 20, 30, ... it's enough to use 2, 3, ... . Of course, you can generalize this rule using the following fact 5*k * 2*j is divisible by 10.
Please modify your code to :
while (!result.equals(BigInteger.valueOf(0))) {
sum = sum.add(result.mod(BigInteger.valueOf(10)));
result = result.divide(BigInteger.valueOf(10));
System.out.println(sum + " "+ result);
}
Here is another way of doing the same.In this, the complexity to compute the sum is O(1).
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main{
public static void main(String[] args){
BigInteger b = BigInteger.valueOf(1);
for(int i=2;i<=5;i++){
b = b.multiply(BigInteger.valueOf(i));
}
//System.out.println(b);
computing the sum below
final BigInteger NINE = BigInteger.valueOf(9);
if(b == BigInteger.ZERO){
System.out.println(b);
}else if(b.mod(NINE) == BigInteger.ZERO){
System.out.println(NINE);
}else{
System.out.println(b.mod(NINE));
}
}`
}

Is there a method that calculates a factorial in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 7 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I didn't find it, yet. Did I miss something?
I know a factorial method is a common example program for beginners. But wouldn't it be useful to have a standard implementation for this one to reuse?
I could use such a method with standard types (Eg. int, long...) and with BigInteger / BigDecimal, too.
Apache Commons Math has a few factorial methods in the MathUtils class.
public class UsefulMethods {
public static long factorial(int number) {
long result = 1;
for (int factor = 2; factor <= number; factor++) {
result *= factor;
}
return result;
}
}
Big Numbers version by HoldOffHunger:
public static BigInteger factorial(BigInteger number) {
BigInteger result = BigInteger.valueOf(1);
for (long factor = 2; factor <= number.longValue(); factor++) {
result = result.multiply(BigInteger.valueOf(factor));
}
return result;
}
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.
Bare naked factorials are rarely needed in practice. Most often you will need one of the following:
1) divide one factorial by another, or
2) approximated floating-point answer.
In both cases, you'd be better with simple custom solutions.
In case (1), say, if x = 90! / 85!, then you'll calculate the result just as x = 86 * 87 * 88 * 89 * 90, without a need to hold 90! in memory :)
In case (2), google for "Stirling's approximation".
Use Guava's BigIntegerMath as follows:
BigInteger factorial = BigIntegerMath.factorial(n);
(Similar functionality for int and long is available in IntMath and LongMath respectively.)
Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.
i believe this would be the fastest way, by a lookup table:
private static final long[] FACTORIAL_TABLE = initFactorialTable();
private static long[] initFactorialTable() {
final long[] factorialTable = new long[21];
factorialTable[0] = 1;
for (int i=1; i<factorialTable.length; i++)
factorialTable[i] = factorialTable[i-1] * i;
return factorialTable;
}
/**
* Actually, even for {#code long}, it works only until 20 inclusively.
*/
public static long factorial(final int n) {
if ((n < 0) || (n > 20))
throw new OutOfRangeException("n", 0, 20);
return FACTORIAL_TABLE[n];
}
For the native type long (8 bytes), it can only hold up to 20!
20! = 2432902008176640000(10) = 0x 21C3 677C 82B4 0000
Obviously, 21! will cause overflow.
Therefore, for native type long, only a maximum of 20! is allowed, meaningful, and correct.
Because factorial grows so quickly, stack overflow is not an issue if you use recursion. In fact, the value of 20! is the largest one can represent in a Java long. So the following method will either calculate factorial(n) or throw an IllegalArgumentException if n is too big.
public long factorial(int n) {
if (n > 20) throw new IllegalArgumentException(n + " is out of range");
return (1 > n) ? 1 : n * factorial(n - 1);
}
Another (cooler) way to do the same stuff is to use Java 8's stream library like this:
public long factorial(int n) {
if (n > 20) throw new IllegalArgumentException(n + " is out of range");
return LongStream.rangeClosed(1, n).reduce(1, (a, b) -> a * b);
}
Read more on Factorials using Java 8's streams
Apache Commons Math package has a factorial method, I think you could use that.
Short answer is: use recursion.
You can create one method and call that method right inside the same method recursively:
public class factorial {
public static void main(String[] args) {
System.out.println(calc(10));
}
public static long calc(long n) {
if (n <= 1)
return 1;
else
return n * calc(n - 1);
}
}
Try this
public static BigInteger factorial(int value){
if(value < 0){
throw new IllegalArgumentException("Value must be positive");
}
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= value; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
You can use recursion.
public static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
and then after you create the method(function) above:
System.out.println(factorial(number of your choice));
//direct example
System.out.println(factorial(3));
I found an amazing trick to find factorials in just half the actual multiplications.
Please be patient as this is a little bit of a long post.
For Even Numbers:
To halve the multiplication with even numbers, you will end up with n/2 factors. The first factor will be the number you are taking the factorial of, then the next will be that number plus that number minus two. The next number will be the previous number plus the lasted added number minus two. You are done when the last number you added was two (i.e. 2). That probably didn't make much sense, so let me give you an example.
8! = 8 * (8 + 6 = 14) * (14 + 4 = 18) * (18 + 2 = 20)
8! = 8 * 14 * 18 * 20 which is **40320**
Note that I started with 8, then the first number I added was 6, then 4, then 2, each number added being two less then the number added before it. This method is equivalent to multiplying the least numbers with the greatest numbers, just with less multiplication, like so:
8! = 1 * 2 * 3 * 4 * 5 * 6 * 7 *
8! = (1 * 8) * (2 * 7) * (3 * 6) * (4 * 5)
8! = 8 * 14 * 18 * 20
Simple isn't it :)
Now For Odd Numbers: If the number is odd, the adding is the same, as in you subtract two each time, but you stop at three. The number of factors however changes. If you divide the number by two, you will end up with some number ending in .5. The reason is that if we multiply the ends together, that we are left with the middle number. Basically, this can all be solved by solving for a number of factors equal to the number divided by two, rounded up. This probably didn't make much sense either to minds without a mathematical background, so let me do an example:
9! = 9 * (9 + 7 = 16) * (16 + 5 = 21) * (21 + 3 = 24) * (roundUp(9/2) = 5)
9! = 9 * 16 * 21 * 24 * 5 = **362880**
Note: If you don't like this method, you could also just take the factorial of the even number before the odd (eight in this case) and multiply it by the odd number (i.e. 9! = 8! * 9).
Now let's implement it in Java:
public static int getFactorial(int num)
{
int factorial=1;
int diffrennceFromActualNum=0;
int previousSum=num;
if(num==0) //Returning 1 as factorial if number is 0
return 1;
if(num%2==0)// Checking if Number is odd or even
{
while(num-diffrennceFromActualNum>=2)
{
if(!isFirst)
{
previousSum=previousSum+(num-diffrennceFromActualNum);
}
isFirst=false;
factorial*=previousSum;
diffrennceFromActualNum+=2;
}
}
else // In Odd Case (Number * getFactorial(Number-1))
{
factorial=num*getFactorial(num-1);
}
return factorial;
}
isFirst is a boolean variable declared as static; it is used for the 1st case where we do not want to change the previous sum.
Try with even as well as for odd numbers.
The only business use for a factorial that I can think of is the Erlang B and Erlang C formulas, and not everyone works in a call center or for the phone company. A feature's usefulness for business seems to often dictate what shows up in a language - look at all the data handling, XML, and web functions in the major languages.
It is easy to keep a factorial snippet or library function for something like this around.
A very simple method to calculate factorials:
private double FACT(double n) {
double num = n;
double total = 1;
if(num != 0 | num != 1){
total = num;
}else if(num == 1 | num == 0){
total = 1;
}
double num2;
while(num > 1){
num2 = num - 1;
total = total * num2;
num = num - 1;
}
return total;
}
I have used double because they can hold massive numbers, but you can use any other type like int, long, float, etc.
P.S. This might not be the best solution but I am new to coding and it took me ages to find a simple code that could calculate factorials so I had to write the method myself but I am putting this on here so it helps other people like me.
You can use recursion version as well.
static int myFactorial(int i) {
if(i == 1)
return;
else
System.out.prinln(i * (myFactorial(--i)));
}
Recursion is usually less efficient because of having to push and pop recursions, so iteration is quicker. On the other hand, recursive versions use fewer or no local variables which is advantage.
We need to implement iteratively. If we implement recursively, it will causes StackOverflow if input becomes very big (i.e. 2 billions). And we need to use unbound size number such as BigInteger to avoid an arithmatic overflow when a factorial number becomes bigger than maximum number of a given type (i.e. 2 billion for int). You can use int for maximum 14 of factorial and long for maximum 20
of factorial before the overflow.
public BigInteger getFactorialIteratively(BigInteger input) {
if (input.compareTo(BigInteger.ZERO) <= 0) {
throw new IllegalArgumentException("zero or negatives are not allowed");
}
BigInteger result = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(input) <= 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(i);
}
return result;
}
If you can't use BigInteger, add an error checking.
public long getFactorialIteratively(long input) {
if (input <= 0) {
throw new IllegalArgumentException("zero or negatives are not allowed");
} else if (input == 1) {
return 1;
}
long prev = 1;
long result = 0;
for (long i = 2; i <= input; i++) {
result = prev * i;
if (result / prev != i) { // check if result holds the definition of factorial
// arithmatic overflow, error out
throw new RuntimeException("value "+i+" is too big to calculate a factorial, prev:"+prev+", current:"+result);
}
prev = result;
}
return result;
}
Factorial is highly increasing discrete function.So I think using BigInteger is better than using int.
I have implemented following code for calculation of factorial of non-negative integers.I have used recursion in place of using a loop.
public BigInteger factorial(BigInteger x){
if(x.compareTo(new BigInteger("1"))==0||x.compareTo(new BigInteger("0"))==0)
return new BigInteger("1");
else return x.multiply(factorial(x.subtract(new BigInteger("1"))));
}
Here the range of big integer is
-2^Integer.MAX_VALUE (exclusive) to +2^Integer.MAX_VALUE,
where Integer.MAX_VALUE=2^31.
However the range of the factorial method given above can be extended up to twice by using unsigned BigInteger.
We have a single line to calculate it:
Long factorialNumber = LongStream.rangeClosed(2, N).reduce(1, Math::multiplyExact);
A fairly simple method
for ( int i = 1; i < n ; i++ )
{
answer = answer * i;
}
/**
import java liberary class
*/
import java.util.Scanner;
/* class to find factorial of a number
*/
public class factorial
{
public static void main(String[] args)
{
// scanner method for read keayboard values
Scanner factor= new Scanner(System.in);
int n;
double total = 1;
double sum= 1;
System.out.println("\nPlease enter an integer: ");
n = factor.nextInt();
// evaluvate the integer is greater than zero and calculate factorial
if(n==0)
{
System.out.println(" Factorial of 0 is 1");
}
else if (n>0)
{
System.out.println("\nThe factorial of " + n + " is " );
System.out.print(n);
for(int i=1;i<n;i++)
{
do // do while loop for display each integer in the factorial
{
System.out.print("*"+(n-i) );
}
while ( n == 1);
total = total * i;
}
// calculate factorial
sum= total * n;
// display sum of factorial
System.out.println("\n\nThe "+ n +" Factorial is : "+" "+ sum);
}
// display invalid entry, if enter a value less than zero
else
{
System.out.println("\nInvalid entry!!");
}System.exit(0);
}
}
public static int fact(int i){
if(i==0)
return 0;
if(i>1){
i = i * fact(--i);
}
return i;
}
public int factorial(int num) {
if (num == 1) return 1;
return num * factorial(num - 1);
}
while loop (for small numbers)
public class factorial {
public static void main(String[] args) {
int counter=1, sum=1;
while (counter<=10) {
sum=sum*counter;
counter++;
}
System.out.println("Factorial of 10 is " +sum);
}
}
I got this from EDX use it! its called recursion
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
with recursion:
public static int factorial(int n)
{
if(n == 1)
{
return 1;
}
return n * factorial(n-1);
}
with while loop:
public static int factorial1(int n)
{
int fact=1;
while(n>=1)
{
fact=fact*n;
n--;
}
return fact;
}
using recursion is the simplest method. if we want to find the factorial of
N, we have to consider the two cases where N = 1 and N>1 since in factorial
we keep multiplying N,N-1, N-2,,,,, until 1. if we go to N= 0 we will get 0
for the answer. in order to stop the factorial reaching zero, the following
recursive method is used. Inside the factorial function,while N>1, the return
value is multiplied with another initiation of the factorial function. this
will keep the code recursively calling the factorial() until it reaches the
N= 1. for the N=1 case, it returns N(=1) itself and all the previously built
up result of multiplied return N s gets multiplied with N=1. Thus gives the
factorial result.
static int factorial(int N) {
if(N > 1) {
return n * factorial(N - 1);
}
// Base Case N = 1
else {
return N;
}
public static long factorial(int number) {
if (number < 0) {
throw new ArithmeticException(number + " is negative");
}
long fact = 1;
for (int i = 1; i <= number; ++i) {
fact *= i;
}
return fact;
}
using recursion.
public static long factorial(int number) {
if (number < 0) {
throw new ArithmeticException(number + " is negative");
}
return number == 0 || number == 1 ? 1 : number * factorial(number - 1);
}
source
Using Java 9+, you can use this solution. This uses BigInteger, ideal for holding large numbers.
...
import java.math.BigInteger;
import java.util.stream.Stream;
...
String getFactorial(int n) {
return Stream.iterate(BigInteger.ONE, i -> i.add(BigInteger.ONE)).parallel()
.limit(n).reduce(BigInteger.ONE, BigInteger::multiply).toString();
}
USING DYNAMIC PROGRAMMING IS EFFICIENT
if you want to use it to calculate again and again (like caching)
Java code:
int fact[]=new int[n+1]; //n is the required number you want to find factorial for.
int factorial(int num)
{
if(num==0){
fact[num]=1;
return fact[num];
}
else
fact[num]=(num)*factorial(num-1);
return fact[num];
}

Categories

Resources