kyle bennedy
kyle bennedy

Reputation: 1

How would you convert a string of long integer to BigInteger?

I'm stuck on this portion of my code. I have a string that is stored in the input.

String input = ("831346848 2162638190 2014846560 1070589609 326439737");

The string contains long integers. I'm trying to implement them by converting each long integer into a BigInteger. For example, from the string, I need to do this:

 BigInteger bi1= new BigInteger("831346848");

and so on. The input string is extremely long, so I need to put this in some kind of loop. after I temporarily store it into bi1 I need to perform a b1.modPow(exp,mod). Then repeat the steps for each long integer in the string. That part I understand, but the part I'm confused on is how to put the input string in a loop so it will store it in bi1.

The long integers are separated by a space and each long integer in the string is different lengths.

What is the best way to implement this?

Upvotes: 0

Views: 2147

Answers (5)

sidgate
sidgate

Reputation: 15254

The Java-8 way

List<BigInteger> bigIntegers = Stream.of(input.split(" "))
    .map(BigInteger::new)
    .map(bi -> bi.modPow(exp, bi))
    .collect(Collectors.toList());

Upvotes: 7

KJEjava48
KJEjava48

Reputation: 2055

You need a regular expression like "\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
   List<BigInteger> bigList = new ArrayList<BigInteger>();
   for(String subStr : input.split("\\s+")){
      bigList.add(new BigInteger(subStr));
   }
} catch (Exception ex) {
    // 
}

You can avoid the '+' sign in "\s+" if only one space is there if you like,but its not necessary.

Upvotes: 0

Henrique Viecili
Henrique Viecili

Reputation: 141

BigInteger bi1;
for (String sbigint : input.split(" ")) {
    BigInteger b1 = new BigInteger(sbigint);
    bi1 = b1.modPow(exp, mod);
}

The problem you described seems to missing something, the way it is bi1 will contain the result modPow for the last long integer in your string.

Upvotes: 1

Rakesh KR
Rakesh KR

Reputation: 6527

Split the string by space and store it in a List of BigInteger

String input = "831346848 2162638190 2014846560 1070589609 326439737";

List<BigInteger> bigIntegerList = new ArrayList<BigInteger>();

for(String value : input.split("\\s")){
     bigIntegerList.add(new BigInteger(value));
}

Upvotes: 4

Scary Wombat
Scary Wombat

Reputation: 44854

try

String nums [] = input.split (" ");
for (String num : nums) {
  BigInteger bi1= new BigInteger(num);
  // do whatever
}

Upvotes: 1

Related Questions