Java/Development Class/Big Integer

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Another Big Integer

/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.ru/javaexamples2.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.math.BigInteger;

/**
 * This program displays factorials as the user enters values interactively
 */
public class FactQuoter {
  public static void main(String[] args) throws IOException {
    // This is how we set things up to read lines of text from the user.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    // Loop forever
    for (;;) {
      // Display a prompt to the user
      System.out.print("FactQuoter> ");
      // Read a line from the user
      String line = in.readLine();
      // If we reach the end-of-file,
      // or if the user types "quit", then quit
      if ((line == null) || line.equals("quit"))
        break;
      // Try to parse the line, and compute and print the factorial
      try {
        int x = Integer.parseInt(line);
        System.out.println(x + "! = " + Factorial4.factorial(x));
      }
      // If anything goes wrong, display a generic error message
      catch (Exception e) {
        System.out.println("Invalid Input");
      }
    }
  }
}
/**
 * This version of the program uses arbitrary precision integers, so it does not
 * have an upper-bound on the values it can compute. It uses an ArrayList object
 * to cache computed values instead of a fixed-size array. An ArrayList is like
 * an array, but can grow to any size. The factorial() method is declared
 * "synchronized" so that it can be safely used in multi-threaded programs. Look
 * up java.math.BigInteger and java.util.ArrayList while studying this class.
 * Prior to Java 1.2, use Vector instead of ArrayList
 */
class Factorial4 {
  protected static ArrayList table = new ArrayList(); // create cache
  static { // Initialize the first element of the cache with !0 = 1.
    table.add(BigInteger.valueOf(1));
  }
  /** The factorial() method, using BigIntegers cached in a ArrayList */
  public static synchronized BigInteger factorial(int x) {
    if (x < 0)
      throw new IllegalArgumentException("x must be non-negative.");
    for (int size = table.size(); size <= x; size++) {
      BigInteger lastfact = (BigInteger) table.get(size - 1);
      BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
      table.add(nextfact);
    }
    return (BigInteger) table.get(x);
  }
  /**
   * A simple main() method that we can use as a standalone test program for
   * our factorial() method.
   */
  public static void main(String[] args) {
    for (int i = 0; i <= 50; i++)
      System.out.println(i + "! = " + factorial(i));
  }
}





A trivial reverse-polish stack-based calculator for big numbers

import java.math.BigDecimal;
import java.util.Stack;
/** A trivial reverse-polish stack-based calculator for big numbers */
public class BigNumCalc {
  /** an array of Objects, simulating user input */
  public static Object[] testInput = {
    new BigDecimal("3419229223372036854775807.23343"),
    new BigDecimal("2.0"),
    "*",
  };
  public static void main(String[] args) {
    BigNumCalc calc = new BigNumCalc();
    System.out.println(calc.calculate(testInput));
  }
  Stack s = new Stack();
  public BigDecimal calculate(Object[] input) {
    BigDecimal tmp;
    for (int i = 0; i < input.length; i++) {
      Object o = input[i];
      if (o instanceof BigDecimal) {
        s.push(o);
      } else if (o instanceof String) {
        switch (((String)o).charAt(0)) {
        // + and * are commutative, order doesn"t matter
        case "+":
          s.push(((BigDecimal)s.pop()).add((BigDecimal)s.pop()));
          break;
        case "*":
          s.push(((BigDecimal)s.pop()).multiply((BigDecimal)s.pop()));
          break;
        // - and /, order *does* matter
        case "-":
          tmp = (BigDecimal)s.pop();
          s.push(((BigDecimal)s.pop()).subtract(tmp));
          break;
        case "/":
          tmp = (BigDecimal)s.pop();
          s.push(((BigDecimal)s.pop()).divide(tmp,
            BigDecimal.ROUND_UP));
          break;
        default:
          throw new IllegalStateException("Unknown OPERATOR popped");
        }
      } else {
        throw new IllegalArgumentException("Syntax error in input");
      }
    }
    return (BigDecimal)s.pop();
  }
}





Big Integer demo

import java.math.BigInteger;
import java.util.ArrayList;
/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.ru/javaexamples2.
 */
/**
 * This program computes and displays the factorial of a number specified on the
 * command line. It handles possible user input errors with try/catch.
 */
public class FactComputer {
  public static void main(String[] args) {
    // Try to compute a factorial.
    // If something goes wrong, handle it in the catch clause below.
    try {
      int x = Integer.parseInt(args[0]);
      System.out.println(x + "! = " + Factorial4.factorial(x));
    }
    // The user forgot to specify an argument.
    // Thrown if args[0] is undefined.
    catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("You must specify an argument");
      System.out.println("Usage: java FactComputer <number>");
    }
    // The argument is not a number. Thrown by Integer.parseInt().
    catch (NumberFormatException e) {
      System.out.println("The argument you specify must be an integer");
    }
    // The argument is < 0. Thrown by Factorial4.factorial()
    catch (IllegalArgumentException e) {
      // Display the message sent by the factorial() method:
      System.out.println("Bad argument: " + e.getMessage());
    }
  }
}
/**
 * This version of the program uses arbitrary precision integers, so it does not
 * have an upper-bound on the values it can compute. It uses an ArrayList object
 * to cache computed values instead of a fixed-size array. An ArrayList is like
 * an array, but can grow to any size. The factorial() method is declared
 * "synchronized" so that it can be safely used in multi-threaded programs. Look
 * up java.math.BigInteger and java.util.ArrayList while studying this class.
 * Prior to Java 1.2, use Vector instead of ArrayList
 */
class Factorial4 {
  protected static ArrayList table = new ArrayList(); // create cache
  static { // Initialize the first element of the cache with !0 = 1.
    table.add(BigInteger.valueOf(1));
  }
  /** The factorial() method, using BigIntegers cached in a ArrayList */
  public static synchronized BigInteger factorial(int x) {
    if (x < 0)
      throw new IllegalArgumentException("x must be non-negative.");
    for (int size = table.size(); size <= x; size++) {
      BigInteger lastfact = (BigInteger) table.get(size - 1);
      BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
      table.add(nextfact);
    }
    return (BigInteger) table.get(x);
  }
  /**
   * A simple main() method that we can use as a standalone test program for
   * our factorial() method.
   */
  public static void main(String[] args) {
    for (int i = 0; i <= 50; i++)
      System.out.println(i + "! = " + factorial(i));
  }
}





Demonstrate large numbers

import java.math.*;
/**
 * Demonstrate large numbers.
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: BigNums.java,v 1.4 2004/02/09 03:33:56 ian Exp $
 */
public class BigNums {
  public static void main(String[] argv) {
    //+
    System.out.println("Here"s Long.MAX_VALUE: " + Long.MAX_VALUE);
    BigInteger bInt = new BigInteger("3419229223372036854775807");
    System.out.println("Here"s a bigger number: " + bInt);
    System.out.println("Here it is as a double: " + bInt.doubleValue());
    //-
  }
}