import java.math.BigInteger; /** * Natural Number * Implementation of a natural number using BigInteger * Definition of a natural number can be found in Natural.isNatural(BigInteger n) * * Use this code freely, but be sure to leave this comment in the code :) * * @author Doug Swain (doug@theswain.net) * http://www.theswain.net */ @SuppressWarnings("serial") public class Natural extends BigInteger { /** * Constructor to create a Natural from an array of bytes * * @param naturalNumber The value of the natural number * @throws NumberFormatException If the number is not a natural number */ public Natural(byte[] naturalNumber) throws NumberFormatException { super(naturalNumber); if (!isNatural(this)) throw new NumberFormatException("The number n must be a natural number - " + naturalNumber + " >= 0"); } /** * Constructor to create a Natural from an array of bytes * * @param naturalNumber The value of the natural number * @throws NumberFormatException If the number is not a natural number */ public Natural(String naturalNumber) throws NumberFormatException { super(naturalNumber); if (!isNatural(this)) throw new NumberFormatException("The number n must be a natural number - " + naturalNumber + " >= 0"); } /** * Defines whether a number (n) is natural or not * * @param BigInteger n The number to verify is natural * @return boolean Whether or not n is natural or not */ public static boolean isNatural(BigInteger n) { return n.compareTo(BigInteger.ZERO) >= 0; } /** * Main method used for simple unit testing */ public static void main(String[] args) { Natural n = null; try { n = new Natural("7598732975932646".getBytes()); System.out.println("Natural: " + n); n = new Natural("563476592396"); System.out.println("Natural: " + n); } catch (NumberFormatException nfe) { System.out.println("Failed: " + nfe); } Exception nfe = null; try { n = new Natural("3.141592653589793238462643383279502884"); } catch (NumberFormatException e) { nfe = e; } if (nfe == null) System.out.println("Failed"); else System.out.println("Success"); } }