How can I implement the BigInteger class into my code? - java

I am working on a program that is supposed to return the position of a given number along the Fibonacci Sequence.
Simple enough, but the test-cases on Codeabbey are over 100 digits long. This is more than the long primitive data type can handle. I know I need to use BigInteger, but I am not sure how to implement it into my code. I read that BigInteger is immutable? What does this mean?
Here is my code:
import java.util.Scanner;
class codeabbey67
{
public static void main(String[] Args)
{
Scanner input = new Scanner(System.in);
System.out.print("Sets: ");
int sets = input.nextInt();
long A[] = new long[sets];
for(int i = 0; i<sets; i++)
{
long f = 0;
long s = 1;
long next = 0;
long j = 0;
System.out.print("\nVal: ");
long val = input.nextLong();
while(next != val)
{
if(j<= 1)
{
next = 1;
j++;
}
next = f+s;
f = s;
s = next;
j++;
}
A[i] = j;
}
System.out.println("\nRESULTS: ");
for(int j = 0; j<A.length; j++)
System.out.print(A[j] + " ");
}
}
EDIT:
Here is my updated code with BigInteger. Still no luck.
import java.util.Scanner;
import java.math.BigInteger;
class codeabbey67
{
public static void main(String[] Args)
{
Scanner input = new Scanner(System.in);
System.out.print("\n\nSets: ");
int sets = input.nextInt();
int A[] = new int[sets];
for(int i = 0; i<sets; i++)
{
BigInteger f = BigInteger.ZERO;
BigInteger s = BigInteger.ONE;
BigInteger next = BigInteger.ZERO;
BigInteger j = BigInteger.ZERO;
System.out.print("\nVAL: ");
BigInteger val = input.nextBigInteger();
int x = 0;
while(!next.equals(val) && x!= 1000) //until current value at position in sequence equals desired value
{
if(x<= 1)
{
next = BigInteger.ONE;
x++;
}
next = f.add(s);
s=next;
x++;
}
A[i] = x;
}
for(int y = 0; y<A.length; y++)
System.out.print(A[y] + " ");
}
}
EDIT: Figured it out. Thanks for all of the help!

BigInteger comes with methods that can be used to modify the numerical value stored within it. This may be useful to learn how to use BigInteger.
Immutable means that you cannot modify an existing object, you can only create a new one. Think of a class such as java.awt.Color: none of the fields of that class are editable, thus it is immutable. Another example would be the String class.
Because the BigInteger method operations e.g. add (), subtract (), etc. all return a BigInteger object containing the new value after the said operation, you can reassign an existing BigInteger reference variable to the BigInteger object returned by an operation like thus:
BigInteger sum = new BigInteger ("0", 10);
sum = sum.add (new BigInteger ("123", 10)); //sum’s value is now 123
In your case, since you are already using a long, you can use the BigInteger method valueOf (), which accepts a long parameter and returns a BigInteger object consisting of the long value. E.g.
BigInteger sum = BigInteger.valueOf (123);//sum’s value is now set to 123

Like #dabigone said, you can use BigInteger instead of implementing it yourself, I try to change your code using BigInteger for this Codeabbey67 as :
public class Codeabbey67 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
while (N-- > 0) {
BigInteger bi = new BigInteger(in.next());
BigInteger i = new BigInteger("0");
BigInteger j = new BigInteger("1");
int idx = 0;
while (!i.equals(bi) && idx <= 1000) {
j = i.add(j);
i = j.subtract(i);
idx++;
}
System.out.print(idx + " ");
}
}

Related

Erroneous behaviour of Java 8 Stream.sum()

Today while solving this question on HackerRank I used Array stream .sum() function to sum all the entries and proceeded with my algorithm. But for sum reason I found that my algorithm fails for some cases. I used diff to find out it passes 99% cases and for 1% the output is nearly equal but is less than the original answer. That's why I replaced the stream .sum() with a for loop and unexpectedly it passed all the test cases. I tried but couldn't ascertain this uncertain behaviour.
My implementation using stream.sum() :
public class MandragoraForest {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
for (int i = in.nextInt(); i > 0; i--) {
int number = in.nextInt();
int[] h = new int[number];
for (int j = 0; j < number; j++) h[j] = in.nextInt();
System.out.println(new MandragoraForestSolver().solve(h));
}
}
}
class MandragoraForestSolver {
public long solve(int[] h) {
if (h.length==1) return h[0];
Arrays.parallelSort(h);
long sum = Arrays.stream(h)
.sum();
long ans = -1;
for (long i=0, strength = 2; i<h.length; i++, strength++) {
sum -= h[(int)i];
ans = Math.max(ans, strength * sum);
}
return ans;
}
}
Implementation without Java stream :
public class MandragoraForest {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
for (int i = in.nextInt(); i > 0; i--) {
int number = in.nextInt();
int[] h = new int[number];
long sum = 0;
for (int j = 0; j < number; j++) {
h[j] = in.nextInt();
sum += h[j];
}
System.out.println(new MandragoraForestSolver().solve(h, sum));
}
}
}
class MandragoraForestSolver {
public long solve(int[] h, long sum) {
if (h.length==1) return h[0];
Arrays.parallelSort(h);
long ans = -1;
for (long i=0, strength = 2; i<h.length; i++, strength++) {
sum -= h[(int)i];
ans = Math.max(ans, strength * sum);
}
return ans;
}
}
Is there something that I'am missing out ? What could be the reason for this behaviour?
There is one significant difference between using a stream and a loop - the possibility of arithmetic overflow.
Arrays.stream(int[]) returns an IntStream, whose sum() method returns an int result. If the sum exceeds Integer.MAX_VALUE, a silent integer overflow will occur.
However your loop sums by adding int values to a long total, which would not suffer from arithmetic overflow.
The sum of integers in one of the tests must exceed Integer.MAX_VALUE, testing that a long is used to (correctly) calculate the total.
If you want to use a stream to sum, you need to convert the IntStream to a LongStream, which you can do like this:
long sum = Arrays.stream(big).asLongStream().sum();

Modular Exponentiation Issue in Java

import java.util.Scanner;
class codeabbey145
{
public static void main(String[] Args)
{
Scanner input = new Scanner(System.in);
double A = 0;
double B = 0;
double M = 0;
System.out.println("\n\nHow many sets?");
int s = input.nextInt();
double X[] = new double[s];
for(int i = 0; i<s; i++)
{
System.out.println("A: ");
A = input.nextDouble();
System.out.println("B: ");
B = input.nextDouble();
System.out.println("M: ");
M = input.nextDouble();
X[i] = (Math.pow(A, B)) % M; //(A^B)%M
}
for(int j = 0; j<s; j++)
{
System.out.print(Math.round(X[j]) + " ");
}
}
}
I have been attempting to complete Exercise 145 on Codeabbey.com
The formula given for modular exponentiation is: (A^B)%M
I tried my best to implement this formula into my code, but the answers I have been getting are incorrect. Anybody know why this might be?
Thanks in advance
You code is Absolutely correct : Check here .
Probably you should use BigInteger: for handling large numbers , double is never recommended.
Here is the working example: check this live demo
Code
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
System.out.println("\n\nHow many sets?");
int s = input.nextInt();
BigInteger[] X = new BigInteger[s];
for (int i = 0; i < s; i++) {
System.out.println("A: ");
BigInteger A = input.nextBigInteger();
System.out.println("B: ");
BigInteger B = input.nextBigInteger();
System.out.println("M: ");
BigInteger M = input.nextBigInteger();
X[i] = A.modPow(B, M); //(A^B)%M
}
for (int i = 0; i < X.length; i++) {
System.out.println(X[i]);
}
}
I have attempted this question on CodeAbbey.
My solution was accepted.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
int s = input.nextInt();
BigInteger[] X = new BigInteger[s];
for (int i = 0; i < s; i++) {
BigInteger A = input.nextBigInteger();
BigInteger B = input.nextBigInteger();
BigInteger M = input.nextBigInteger();
X[i] = A.modPow(B, M);
}
for (int i = 0; i < X.length; i++) {
System.out.println(X[i]+" ");
}
}
}
Most likely the values are too big to fit into a double, so they overflow. Your best bet is probably to implement using BigInteger objects.
BigInteger has pow and mod functions that you can use for your calculations.

Wordlist generator that support BigIntegers for Huge Numbers

I need a help to complete a program that will generate a wordlist from chosen characters and length (it need to support a big length).
At first you need to fix this both by adding the length (wordlength) wanted and making a string of the specified characters(alphabet).
So the full number of words is:
long MAX_WORDS = (long) Math.pow(alphabet.length(), wordlength);
Actually, I made it and it work (for the example of short word of 2 or 66 characters).
import java.math.BigInteger;
public class wordlistgenenreg {
public static void main(String[] args) {
generate();
}
private static void generate(){
int wordlength =2;
String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~";
final long MAX_WORDS = (long) Math.pow(alphabet.length(), wordlength);
final int RADIX = alphabet.length();
for (long i = 0; i < MAX_WORDS; i++) {
int[] indices = convertToRadix(RADIX, i, wordlength);
char[] word = new char[wordlength];
for (int k = 0; k < wordlength; k++) {word[k] = alphabet.charAt(indices[k]);}
String fullword=new String(word);
System.out.println(fullword);
}
System.out.println("completed!");
}
private static int[] convertToRadix(int radix, long number, int wordlength) {
int[] indices = new int[wordlength];
for (int i = wordlength - 1; i >= 0; i--) {
if (number > 0) {
int rest = (int) (number % radix);
number /= radix;
indices[i] = rest;
} else {
indices[i] = 0;
}
}
return indices;
}
}
but there are a problem when i want to generate a really big string of 64 characters from 66. Because:
MAX_WORDS = 66^64 = 282365657377235405270307754780751252031361330095689004197961218014051357270480550051149871489969454245263206971867136
So I tried to change it to make it work with the BigInteger. But us a result, I always obtain the String:
"0000000000000000000000000000000000000000000000000000000000000000"
So there are a problem that i didn't figure it out. This my work on changing it:
import java.math.BigInteger;
public class wordlistgen {
public static void main(String[] args) {
generate();
}
private static void generate() {
int wordlength = 64;
String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~";
BigInteger max_words=new BigInteger("282365657377235405270307754780751252031361330095689004197961218014051357270480550051149871489969454245263206971867136");
final int RADIX = alphabet.length();
BigInteger plus=BigInteger.valueOf(1);
for (BigInteger i = new BigInteger("0"); i.compareTo(max_words) <0; i.add(plus)) {
int[] indices = convertToRadix(RADIX, i, wordlength);
char[] word = new char[wordlength];
for (int k = 0; k < wordlength; k++) {word[k] = alphabet.charAt(indices[k]);}
String fullword=new String(word);
System.out.println(fullword);
}
}
private static int[] convertToRadix(int radix, BigInteger i2, int wordlength) {
BigInteger zero=BigInteger.valueOf(0);
BigInteger big_radix=BigInteger.valueOf(radix);
int[] indices = new int[wordlength];
for (int i = wordlength - 1; i >= 0; i--) {
if (i2.compareTo(zero)==0) {
BigInteger rest =i2.remainder(big_radix);
BigInteger ab=i2.divide(big_radix);
i2=ab;
indices[i] = rest.intValue();
} else {
indices[i] = 0;
}
}
return indices;
}
}
This is the if from your original version:
if (number > 0) {
int rest = (int) (number % radix);
number /= radix;
indices[i] = rest;
} else {
indices[i] = 0;
}
And the same if in the BigInteger version:
if (i2.compareTo(zero)==0) {
BigInteger rest =i2.remainder(big_radix);
BigInteger ab=i2.divide(big_radix);
i2=ab;
indices[i] = rest.intValue();
} else {
indices[i] = 0;
}
As you can see, in your new if, you are asking if number == 0 instead of number > 0. So you always end up in the else.
As a side note: you are running a loop from 0 to your max_words. If each iteration takes merely a nanosecond to complete, it will still take 368788667672120349090672500612638816231217766896306723928560063188563281831044121479026746095987887263264265 years. Enough time for the universe to disintegrate into full entropy. I'd suggest re-thinking your algorithm.

Fibonacci sequence in Java using for statements

I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}

Find factorial of large numbers in Java

I tried to find the factorial of a large number e.g. 8785856 in a typical way using for-loop and double data type.
But it is displaying infinity as the result, may be because it is exceeding its limit.
So please guide me the way to find the factorial of a very large number.
My code:
class abc
{
public static void main (String[]args)
{
double fact=1;
for(int i=1;i<=8785856;i++)
{
fact=fact*i;
}
System.out.println(fact);
}
}
Output:-
Infinity
I am new to Java but have learned some concepts of IO-handling and all.
public static void main(String[] args) {
BigInteger fact = BigInteger.valueOf(1);
for (int i = 1; i <= 8785856; i++)
fact = fact.multiply(BigInteger.valueOf(i));
System.out.println(fact);
}
You might want to reconsider calculating this huge value. Wolfram Alpha's Approximation suggests it will most certainly not fit in your main memory to be displayed.
This code should work fine :-
public class BigMath {
public static String factorial(int n) {
return factorial(n, 300);
}
private static String factorial(int n, int maxSize) {
int res[] = new int[maxSize];
res[0] = 1; // Initialize result
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4... * n
for (int x = 2; x <= n; x++) {
res_size = multiply(x, res, res_size);
}
StringBuffer buff = new StringBuffer();
for (int i = res_size - 1; i >= 0; i--) {
buff.append(res[i]);
}
return buff.toString();
}
/**
* This function multiplies x with the number represented by res[]. res_size
* is size of res[] or number of digits in the number represented by res[].
* This function uses simple school mathematics for multiplication.
*
* This function may value of res_size and returns the new value of res_size.
*/
private static int multiply(int x, int res[], int res_size) {
int carry = 0; // Initialize carry.
// One by one multiply n with individual digits of res[].
for (int i = 0; i < res_size; i++) {
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod / 10; // Put rest in carry
}
// Put carry in res and increase result size.
while (carry != 0) {
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
}
return res_size;
}
/** Driver method. */
public static void main(String[] args) {
int n = 100;
System.out.printf("Factorial %d = %s%n", n, factorial(n));
}
}
Hint: Use the BigInteger class, and be prepared to give the JVM a lot of memory. The value of 8785856! is a really big number.
Use the class BigInteger. ( I am not sure if that will even work for such huge integers )
Infinity is a special reserved value in the Double class used when you have exceed the maximum number the a double can hold.
If you want your code to work, use the BigDecimal class, but given the input number, don't expect your program to finish execution any time soon.
The above solutions for your problem (8785856!) using BigInteger would take literally hours of CPU time if not days. Do you need the exact result or would an approximation suffice?
There is a mathematical approach called "Sterling's Approximation
" which can be computed simply and fast, and the following is Gosper's improvement:
import java.util.*;
import java.math.*;
class main
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int i;
int n=sc.nextInt();
BigInteger fact = BigInteger.valueOf(1);
for ( i = 1; i <= n; i++)
{
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println(fact);
}
}
Try this:
import java.math.BigInteger;
public class LargeFactorial
{
public static void main(String[] args)
{
int n = 50;
}
public static BigInteger factorial(int n)
{
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
result = result.multiply(new BigInteger(i + ""));
return result;
}
}
Scanner r = new Scanner(System.in);
System.out.print("Input Number : ");
int num = r.nextInt();
int ans = 1;
if (num <= 0) {
ans = 0;
}
while (num > 0) {
System.out.println(num + " x ");
ans *= num--;
}
System.out.println("\b\b=" + ans);
public static void main (String[] args) throws java.lang.Exception
{
BigInteger fact= BigInteger.ONE;
int factorialNo = 8785856 ;
for (int i = 2; i <= factorialNo; i++) {
fact = fact.multiply(new BigInteger(String.valueOf(i)));
}
System.out.println("Factorial of the given number is = " + fact);
}
import java.util.Scanner;
public class factorial {
public static void main(String[] args) {
System.out.println("Enter the number : ");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
factorial f=new factorial();
int result=f.fact(n);
System.out.println("factorial of "+n+" is "+result);
}
int fact(int a)
{
if(a==1)
return 1;
else
return a*fact(a-1);
}
}

Categories

Resources