How to use BigInteger?

Viewed 342427

I have this piece of code, which is not working:

BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 5000; i++) {
    if (isPrim(i)) {
        sum.add(BigInteger.valueOf(i));
    }
}

The sum variable is always 0. What am I doing wrong?

10 Answers

Biginteger is an immutable class. You need to explicitly assign value of your output to sum like this:

sum = sum.add(BigInteger.valueof(i));    

Suppose sometimes our input value is too big to store integer value eg.123456789123456789 In that case, standard datatype like long can't handle it. But Java provides a class "BigInteger". It helps us to pass and access huge value. Please see the below exam to clear the concept.

import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        BigInteger B1=new BigInteger("10");
        BigInteger B2=new BigInteger("20");
        B1=sc.nextBigInteger();
        B2=sc.nextBigInteger();
        Solution obj=new Solution();
        obj.Big_Int(B1,B2);
        sc.close();
    }
    
    public void Big_Int(BigInteger a,BigInteger b)
    {
        //BigInteger bi=new BigInteger("1");
        BigInteger bi=BigInteger.TEN;
        bi=a;
        bi=bi.add(b);
        System.out.println(bi);
        bi=a;
        bi=bi.multiply(b);
        System.out.println(bi);
        
    }
}

input: 123456789123456789 1578426354785

output: 123458367549811574 194867449629598334799730885365

Related