Java/Data Type/BigInteger

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

Содержание

and operation on BigInteger

 

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);
  }
}





antNot operation on BigInteger

 
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);
  }
}





BigInteger.isProbablePrime

  
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.");
  }
}





Calculate the power on a BigInteger

 
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);
  }
}





Clear a bit in a BigInteger

 
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);
  }
}





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

 
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).
 * <P>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));
  }
}





Convert BigInteger into another radix number

 
 
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));
  }
}





Create a BigInteger using the byte array

 
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);
  }
}





Create BigInteger from byte array

 
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);
  }
}





Create BigInteger via long type variable

 
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);
  }
}





Create BigInteger via string

 
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);
  }
}





Demonstration of high-precision integer arithmetic with the BigInteger class

 
/*
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");
      }
    }
  }
}





Divide one BigInteger from another BigInteger

 
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);
  }
}





Do math operation for BigInteger

 
 
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);
  }
}





Flip a bit in a BigInteger

 
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);
  }
}





Get byte array from BigInteger

 
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();
  }
}





Get the value of a bit

 
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); 
  }
}





Multiply one BigInteger to another BigInteger

 
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);
  }
}





Negate a BigInteger

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





not operation for BigInteger

 
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();
  }
}





Operate with big integer values in code

 

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);
  }
}





Operating with Big Integer Values

 
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);
  }
}





or operation for BigInteger

 
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);
  }
}





Parse binary string

 
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();
  }
}





Parse decimal string to create BigInteger

 
import java.math.BigInteger;
public class Main {
  public static void main(String[] argv) throws Exception {
    BigInteger bi = new BigInteger("1183728");
  }
}





Parse hexadecimal string to create BigInteger

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





Parse octal string to create BigInteger

 
import java.math.BigInteger;
public class Main {
  public static void main(String[] argv) throws Exception {
    BigInteger bi = new BigInteger("4407760", 8);
  }
}





Parsing and Formatting a Big Integer into Binary

 
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); 
  }
}





Parsing and Formatting a Big Integer into decimal

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





Parsing and Formatting a Big Integer into octal

 
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);
  }
}





Parsing and Formatting a Byte Array into Binary

 
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);
  }
}





Parsing and Formatting a Byte Array into decimal

 
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(); 
  }
}





Parsing and Formatting a Byte Array into Hexadecimal

 

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;
    }
  }
}





Parsing and Formatting a Byte Array into Octal

 

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);
  }
}





Performing Bitwise Operations with BigInteger

 
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); 
  }
}





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

 
  
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();
  }
}





Set a bit for BigInteger

 
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);
  }
}





Shift right in a BigInteger

 
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);
  }
}





Shift the bits in a BigInteger

 
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);
  }
}





Subtract one BigInteger from another BigInteger

 

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);
  }
}





xor a BigInteger

 
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);
  }
}