0
Factorial Loops
Can someone help me with this factorial loop plz? Im trying to display the factorials for 1-10 but its not coming out corrct?..... https://code.sololearn.com/cqVNrCMhqER6/?ref=app
7 Respuestas
+ 5
you have to use long as the answer is too big and can't accommodate in an integer variable
+ 2
Or you can also use BigInteger for that.
https://www.google.com/amp/s/www.geeksforgeeks.org/biginteger-class-in-java/amp/
+ 2
https://code.sololearn.com/cUbvU1qYxfIH/?ref=app
That's how you should do that
+ 2
import java.math.BigInteger;
public class Factorials {
public static void main(String[] args) {
int number = 1;
BigInteger factor = new BigInteger("1");
int i =1;
for(number = 1; number <= 10; number++)
{
for(i = 1; i <= number; i++)
factor = factor.multiply(BigInteger.valueOf(i));
System.out.println(factor);
}
}}
+ 1
int is enough
if you want 10x calculate factorial like 1*2*3... you must start each next iteration with factor=1 but you start with last factorial like 120*1*2*3... so
for(number = 1; number <= 10; number++)
{
factor=1; // added
for(i = 1; i <= number; i++)
factor *=i;
System.out.println(factor);
}
+ 1
Thank You Ver Much!
restarting the iteration w/factor =1 solved it......
0
I adjusted the type to long but the math still doesnt come out right?...
https://code.sololearn.com/cqVNrCMhqER6/?ref=app