Java/Data Type/BigInteger

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

and operation on BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.and(bi);
 }

}

 </source>
   
  
 
  



antNot operation on BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.andNot(bi);
 }

}


 </source>
   
  
 
  



BigInteger.isProbablePrime

   <source lang="java">
 

import java.math.BigInteger; public class BigNumApp {

 public static void main(String args[]) {
   BigInteger n = new BigInteger("1000000000000");
   BigInteger one = new BigInteger("1");
   while (!n.isProbablePrime(7))
     n = n.add(one);
   System.out.println(n.toString(10) + " is probably prime.");
   System.out.println("It is " + n.bitLength() + " bits in length.");
 }

}

 </source>
   
  
 
  



Calculate the power on a BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi1 = new BigInteger("1234567890123456890");
   int exponent = 2;
   bi1 = bi1.pow(exponent);
 }

}

 </source>
   
  
 
  



Clear a bit in a BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.clearBit(3);
 }

}

 </source>
   
  
 
  



Compute the Palindrome of a number by adding the number composed of

   <source lang="java">

import java.math.BigInteger; /** Compute the Palindrome of a number by adding the number composed of

* its digits in reverse order, until a Palindrome occurs.
* e.g., 42->66 (42+24); 1951->5995 (1951+1591=3542; 3542+2453=5995).
*

TODO: Do we need to handle negative numbers? * @author Ian Darwin, http://www.darwinsys.ru/ * @version $Id: PalindromeBig.java,v 1.3 2004/02/09 03:33:57 ian Exp $. */ public class PalindromeBig { public static boolean verbose = true; public static void main(String[] argv) { for (int i=0; i<argv.length; i++) try { BigInteger l = new BigInteger(argv[i]); if (l.rupareTo(BigInteger.ZERO) < 0) { System.err.println(argv[i] + " -> TOO SMALL"); continue; } System.out.println(argv[i] + "->" + findPalindrome(l)); } catch (NumberFormatException e) { System.err.println(argv[i] + "-> INVALID"); } catch (IllegalStateException e) { System.err.println(argv[i] + "-> " + e); } } /** find a palindromic number given a starting point, by * calling ourself until we get a number that is palindromic. */ public static BigInteger findPalindrome(BigInteger num) { if (num.rupareTo(BigInteger.ZERO) < 0) throw new IllegalStateException("negative"); if (isPalindrome(num)) return num; if (verbose) System.out.println("Trying " + num); return findPalindrome(num.add(reverseNumber(num))); } /** A ridiculously large number */ protected static final int MAX_DIGITS = 255; /** Check if a number is palindromic. */ public static boolean isPalindrome(BigInteger num) { String digits = num.toString(); int numDigits = digits.length(); if (numDigits >= MAX_DIGITS) { throw new IllegalStateException("too big"); } // Consider any single digit to be as palindromic as can be if (numDigits == 1) return true; for (int i=0; i<numDigits/2; i++) { // System.out.println( // digits.charAt(i) + " ? " + digits.charAt(numDigits - i - 1)); if (digits.charAt(i) != digits.charAt(numDigits - i - 1)) return false; } return true; } static BigInteger reverseNumber(BigInteger num) { String digits = num.toString(); int numDigits = digits.length(); char[] sb = new char[numDigits]; for (int i=0; i<digits.length(); i++) { sb[i] = digits.charAt(numDigits - i - 1); } // Debug.println("rev", // "reverseNumber(" + digits + ") -> " + "\"" + sb + "\""); return new BigInteger(new String(sb)); } } </source>

Convert BigInteger into another radix number

   <source lang="java">


import java.math.BigInteger; public class Main {

 public static void main(String[] args) {
   BigInteger number = new BigInteger("2008");
   System.out.println("Number      = " + number);
   System.out.println("Binary      = " + number.toString(2));
   System.out.println("Octal       = " + number.toString(8));
   System.out.println("Hexadecimal = " + number.toString(16));
   number = new BigInteger("FF", 16);
   System.out.println("Number      = " + number);
   System.out.println("Number      = " + number.toString(16));
 }

}

 </source>
   
  
 
  



Create a BigInteger using the byte array

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { (byte) 0x12, (byte) 0x0F, (byte) 0xF0 };
   BigInteger bi = new BigInteger(bytes);
 }

}

 </source>
   
  
 
  



Create BigInteger from byte array

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   // A negative value
   byte[] bytes = new byte[] { (byte) 0xFF, 0x00, 0x00 }; // -65536
   // A positive value
   bytes = new byte[] { 0x1, 0x00, 0x00 }; // 65536
   BigInteger bi = new BigInteger(bytes);
 }

}

 </source>
   
  
 
  



Create BigInteger via long type variable

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   // Create via a string
   BigInteger bi1 = new BigInteger("1234567890123456890");
   // Create via a long
   BigInteger bi2 = BigInteger.valueOf(123L);
   bi1 = bi1.add(bi2);
 }

}

 </source>
   
  
 
  



Create BigInteger via string

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   // Create via a string
   BigInteger bi1 = new BigInteger("1234567890123456890");
   // Create via a long
   BigInteger bi2 = BigInteger.valueOf(123L);
   bi1 = bi1.add(bi2);
 }

}

 </source>
   
  
 
  



Demonstration of high-precision integer arithmetic with the BigInteger class

   <source lang="java">

/* Java Programming for Engineers Julio Sanchez Maria P. Canton

ISBN: 0849308100 Publisher: CRC Press

  • /

// Java for Engineers //Filename: BigIFact //Reference: Chapter 22 //Description: // Demonstration of high-precision integer arithmetic // with the BigInteger class. Program calculates the // factorial of a big integer number //Requires: // Keyin class in current directory import java.math.BigInteger; public class BigIFact {

 public static void main(String[] args) {
   int v; // Input
   BigInteger p = BigInteger.valueOf(1); // Factor
   System.out.println("Big integer factorial routine\n");
   v = Keyin.inInt("Enter value: ");
   // Calculate factorial by iteration
   for (int i = 1; i <= v; i++)
     p = p.multiply(BigInteger.valueOf(i));
   // Display result
   System.out.println(p);
 }

} //********************************************************** //********************************************************** //Program: Keyin //Reference: Session 20 //Topics: //1. Using the read() method of the ImputStream class //in the java.io package //2. Developing a class for performing basic console //input of character and numeric types //********************************************************** //********************************************************** class Keyin {

 //*******************************
 //   support methods
 //*******************************
 //Method to display the user"s prompt string
 public static void printPrompt(String prompt) {
   System.out.print(prompt + " ");
   System.out.flush();
 }
 //Method to make sure no data is available in the
 //input stream
 public static void inputFlush() {
   int dummy;
   int bAvail;
   try {
     while ((System.in.available()) != 0)
       dummy = System.in.read();
   } catch (java.io.IOException e) {
     System.out.println("Input error");
   }
 }
 //********************************
 //  data input methods for
 //string, int, char, and double
 //********************************
 public static String inString(String prompt) {
   inputFlush();
   printPrompt(prompt);
   return inString();
 }
 public static String inString() {
   int aChar;
   String s = "";
   boolean finished = false;
   while (!finished) {
     try {
       aChar = System.in.read();
       if (aChar < 0 || (char) aChar == "\n")
         finished = true;
       else if ((char) aChar != "\r")
         s = s + (char) aChar; // Enter into string
     }
     catch (java.io.IOException e) {
       System.out.println("Input error");
       finished = true;
     }
   }
   return s;
 }
 public static int inInt(String prompt) {
   while (true) {
     inputFlush();
     printPrompt(prompt);
     try {
       return Integer.valueOf(inString().trim()).intValue();
     }
     catch (NumberFormatException e) {
       System.out.println("Invalid input. Not an integer");
     }
   }
 }
 public static char inChar(String prompt) {
   int aChar = 0;
   inputFlush();
   printPrompt(prompt);
   try {
     aChar = System.in.read();
   }
   catch (java.io.IOException e) {
     System.out.println("Input error");
   }
   inputFlush();
   return (char) aChar;
 }
 public static double inDouble(String prompt) {
   while (true) {
     inputFlush();
     printPrompt(prompt);
     try {
       return Double.valueOf(inString().trim()).doubleValue();
     }
     catch (NumberFormatException e) {
       System.out
           .println("Invalid input. Not a floating point number");
     }
   }
 }

}


 </source>
   
  
 
  



Divide one BigInteger from another BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi1 = new BigInteger("1234567890123456890");
   BigInteger bi2 = BigInteger.valueOf(123L);
   bi1 = bi1.divide(bi2);
 }

}

 </source>
   
  
 
  



Do math operation for BigInteger

   <source lang="java">


import java.math.BigInteger; public class Main {

 public static void main(String[] args) {
   BigInteger numberA = new BigInteger("98765432123456789");
   BigInteger numberB = BigInteger.TEN;
   numberA = numberA.add(numberB);
   System.out.println("numberA = " + numberA);
   numberA = numberA.multiply(numberB);
   System.out.println("numberA = " + numberA);
   numberA = numberA.subtract(numberB);
   System.out.println("numberA = " + numberA);
   numberA = numberA.divide(numberB);
   System.out.println("numberA = " + numberA);
   numberA = numberA.mod(numberB);
   System.out.println("numberA = " + numberA);
   numberA = numberA.pow(2);
   System.out.println("numberA = " + numberA);
   numberA = numberA.negate();
   System.out.println("numberA = " + numberA);
 }

}

 </source>
   
  
 
  



Flip a bit in a BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.flipBit(3);
 }

}

 </source>
   
  
 
  



Get byte array from BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi = new BigInteger("100100100111111110000", 2);
   byte[] bytes = bi.toByteArray();
 }

}

 </source>
   
  
 
  



Get the value of a bit

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   boolean b = bi.testBit(3); 
   b = bi.testBit(16); 
 }

}

 </source>
   
  
 
  



Multiply one BigInteger to another BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi1 = new BigInteger("1234567890123456890");
   BigInteger bi2 = BigInteger.valueOf(123L);
   bi1 = bi1.multiply(bi2);
 }

}


 </source>
   
  
 
  



Negate a BigInteger

   <source lang="java">


import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi1 = new BigInteger("1234567890123456890");
   bi1 = bi1.negate();
 }

}

 </source>
   
  
 
  



not operation for BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.not();
 }

}

 </source>
   
  
 
  



Operate with big integer values in code

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   // Create via a string
   BigInteger bi1 = new BigInteger("1234567890123456890");
   // Create via a long
   BigInteger bi2 = BigInteger.valueOf(123L);
   bi1 = bi1.add(bi2);
   bi1 = bi1.multiply(bi2);
   bi1 = bi1.subtract(bi2);
   bi1 = bi1.divide(bi2);
   bi1 = bi1.negate();
   int exponent = 2;
   bi1 = bi1.pow(exponent);
 }

}

 </source>
   
  
 
  



Operating with Big Integer Values

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   // Create via a string
   BigInteger bi1 = new BigInteger("1234567890123456890");
   // Create via a long
   BigInteger bi2 = BigInteger.valueOf(123L);
   bi1 = bi1.add(bi2);
 }

}

 </source>
   
  
 
  



or operation for BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.or(bi);
 }

}

 </source>
   
  
 
  



Parse binary string

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi = new BigInteger("100101000111111110000", 2);
   byte[] bytes = bi.toByteArray();
 }

}

 </source>
   
  
 
  



Parse decimal string to create BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi = new BigInteger("1183728");
 }

}

 </source>
   
  
 
  



Parse hexadecimal string to create BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi = new BigInteger("120ff0", 16);
 }

}

 </source>
   
  
 
  



Parse octal string to create BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi = new BigInteger("4407760", 8);
 }

}

 </source>
   
  
 
  



Parsing and Formatting a Big Integer into Binary

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi = new BigInteger("1023");
   // Parse and format to binary
   bi = new BigInteger("1111111111", 2); 
   String s = bi.toString(2); 
 }

}

 </source>
   
  
 
  



Parsing and Formatting a Big Integer into decimal

   <source lang="java">

 

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi = new BigInteger("1023"); 
   String s = bi.toString(); 
 }

}

 </source>
   
  
 
  



Parsing and Formatting a Big Integer into octal

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi = new BigInteger("1000", 8);
   s = bi.toString(8);
 }

}

 </source>
   
  
 
  



Parsing and Formatting a Byte Array into Binary

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { (byte) 0x12, (byte) 0x0F, (byte) 0xF0 };
   // Create a BigInteger using the byte array
   BigInteger bi = new BigInteger(bytes);
   String s = bi.toString(2); 
   System.out.println(s);
 }

}

 </source>
   
  
 
  



Parsing and Formatting a Byte Array into decimal

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { (byte) 0x12, (byte) 0x0F, (byte) 0xF0 };
   BigInteger bi = new BigInteger(bytes);
   // Format to decimal
   String s = bi.toString(); 
 }

}

 </source>
   
  
 
  



Parsing and Formatting a Byte Array into Hexadecimal

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { (byte) 0x12, (byte) 0x0F, (byte) 0xF0 };
   BigInteger bi = new BigInteger(bytes);
   // Format to hexadecimal
   String s = bi.toString(16); 
   if (s.length() % 2 != 0) {
     s = "0" + s;
   }
 }

}

 </source>
   
  
 
  



Parsing and Formatting a Byte Array into Octal

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { (byte) 0x12, (byte) 0x0F, (byte) 0xF0 };
   BigInteger bi = new BigInteger(bytes);
   // Format to octal
   String s = bi.toString(8); 
   System.out.println(s);
 }

}

 </source>
   
  
 
  



Performing Bitwise Operations with BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   boolean b = bi.testBit(3); 
   b = bi.testBit(16); 
 }

}

 </source>
   
  
 
  



Retrieve the current bits in a byte array in twos-complement form.

   <source lang="java">

 

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[]  bytes = new byte[] { 0x1, 0x00, 0x00 };
   BigInteger bi = new BigInteger(bytes);
   bytes = bi.toByteArray();
 }

}

 </source>
   
  
 
  



Set a bit for BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.setBit(3);
 }

}

 </source>
   
  
 
  



Shift right in a BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.shiftRight(1);
 }

}

 </source>
   
  
 
  



Shift the bits in a BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.shiftLeft(3);
 }

}

 </source>
   
  
 
  



Subtract one BigInteger from another BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   BigInteger bi1 = new BigInteger("1234567890123456890");
   BigInteger bi2 = BigInteger.valueOf(123L);
   bi1 = bi1.subtract(bi2);
 }

}

 </source>
   
  
 
  



xor a BigInteger

   <source lang="java">

import java.math.BigInteger; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = new byte[] { 0x1, 0x00, 0x00 }; 
   BigInteger bi = new BigInteger(bytes);
   bi = bi.xor(bi);
 }

}

 </source>