Wednesday 28 September 2016

Chapter 10 Exercise 20, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*10.20 (Approximate e) Programming Exercise 5.26 approximates e using the following
series:

e = 1 + 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . . + 1 / i !



import java.math.BigDecimal;

public class Exercise_10_20 {
 /** Main method */
 public static void main(String[] args) {
  // Displays the e value for i = 100, 200, . . . , and 1000.
  System.out.println("\n The e values for i = 100 to 1000:");
  System.out.println("-----------------------------------");
  System.out.println(" i                e");
  System.out.println("-----------------------------------");
  for (BigDecimal i = new BigDecimal("100"); 
   i.compareTo(new BigDecimal("1000")) <= 0; 
   i = i.add(new BigDecimal("100"))) {
   System.out.println(i + "    " + getE(i));
  }
 }

 /** Return e value for i */
 public static BigDecimal getE(BigDecimal v) {
  BigDecimal one = new BigDecimal("1");
  BigDecimal e = new BigDecimal("0.0");
  for (BigDecimal i = one; i.compareTo(v) <= 0; i = i.add(one)) {
   BigDecimal denominator = i;
   for (BigDecimal k = i.subtract(one); 
    k.compareTo(one) >= 1; 
    k = k.subtract(one)) {
    denominator = denominator.multiply(k);
   }
   // Use 25 digits of precision
   e = e.add(one.divide(denominator, 25, BigDecimal.ROUND_UP));  
  }
  return e;
 }
}

Sunday 25 September 2016

Chapter 10 Exercise 19, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

Chapter 10 Exercise 19:

10.19 (Mersenne prime) A prime number is called a Mersenne prime if it can be writ- ten in the form 2p - 1 for some positive integer p.
Write a program that finds all Mersenne primes with p … 100 and displays the output as shown below. (Hint: You have to use BigInteger to store the number, because it is too big to be stored in long. Your program may take several hours to run.)


import java.math.BigDecimal;

public class Exercise_19 {

    public static void main(String[] args) {

        System.out.printf("%-10s%7s\n", "P", "2 * P -1");
        int numberOfPrimes = 0;
        for (int i = 2; numberOfPrimes < 100; i++) {
            if (isPrime(i)) {
                numberOfPrimes++;
                System.out.printf("%-10d%-10s\n", i, getMersennePrime(i));
            }
        }

    }

    public static boolean isPrime(long n) {

        long square = (long) Math.sqrt(n);
        for (int i = 2; i <= square; i++) {

            if (n % i == 0) {
                return false;
            }
        }

        return true;
    }

    public static BigDecimal getMersennePrime(int p) {

        return new BigDecimal(2).pow(p).subtract(BigDecimal.ONE);
    }
}

Saturday 24 September 2016

Chapter 10 Exercise 18, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

10.18 (Large prime numbers)
Write a program that finds five prime numbers larger than Long.MAX_VALUE.

public class StopWatch {

    private long mStartTime;
    private long mEndTime;
    private long mElapsedPause;
    private int mLastSecond = 0;

    private boolean mIsOn;
    private boolean mIsPaused;

    private int mSeconds;
    private int mMinutes;
    private int mHours;

    public StopWatch() {
        mStartTime = System.currentTimeMillis();
    }

    public long getStartTime() {
        return mStartTime;
    }

    public long getEndTime() {
        return mEndTime;
    }

    public void start() {
        mIsOn = true;
        mStartTime = System.currentTimeMillis();
    }

    public void stop(){
        mEndTime = System.currentTimeMillis();
        mIsOn = false;
    }

    public long getElapsedTime() {
        return mEndTime - mStartTime;
    }

    public long peek() {
        return System.currentTimeMillis() - mStartTime;
    }
    public void pause() {
        mIsPaused = true;
        mElapsedPause = System.currentTimeMillis() - mStartTime;
    }

    public void resume() {
        mIsPaused = false;
        mStartTime = System.currentTimeMillis() - mElapsedPause;
    }

    public boolean isOn() {
        return mIsOn;
    }
    public boolean nextSecond() {
        updateTime();
        if (mSeconds != mLastSecond) {
            mLastSecond = mSeconds;
            return true;
        } else {
            return false;
        }
    }
    public boolean nextFiveSeconds() {
        updateTime();
        return mSeconds % 5 == 0;
    }

    public int getHour(){
        updateTime();
        return mHours;
    }

    public int getMinute(){
        updateTime();
        return mMinutes;
    }

    public int getSeconds(){
        updateTime();
        return mSeconds;
    }

    private void updateTime() {

        long currentTime = peek() / 1000;
        mSeconds = (int)(currentTime % 60);
        currentTime = currentTime / 60;

        mMinutes = (int) (currentTime % 60);
        currentTime = currentTime / 60;

        mHours = (int)(currentTime % 24);

    }

    @Override
    public String toString() {

        updateTime();
        String hours = getTimeFormat(mHours);
        String minutes = getTimeFormat(mMinutes);
        String seconds = getTimeFormat(mSeconds);

        return hours + ":" + minutes + ":" + seconds;
    }

    private String getTimeFormat(int time) {
        return (time > 9) ? time + "" : "0" + time;
    }

    public void reset(){
        stop();
        mHours = 0;
        mMinutes = 0;
        mSeconds = 0;
        mStartTime = 0;
        mEndTime = 0;
    }


    public boolean isPaused() {
        return mIsPaused;
    }
}
import java.math.BigDecimal;
import java.util.ArrayList;
public class Exercise_18 {

    private static ArrayList<Long> primeArray;

    private static StopWatch time = new StopWatch();

    public static void main(String[] args) {

        System.out.println("First using Mersenne algorithm to finishes this exercise..");
        System.out.printf("%-10s%7s\n", "P", "2 * P -1");

        for (int i = 270; i <= 300; i++) {
            if (isPrime2(i)) {
                System.out.printf("%-10d%-10s\n", i, getMersennePrime(i));
            }
        }

        System.out.println("5 prime numbers larger than Long.MAX_VALUE above...");

        System.out.println("\nPlaying around with primes.");
        System.out.println("Loading prime array...");
        primeArray = new primeArrayClass().getPrimeArrayList();
        System.out.println("loading finished... array size: " + primeArray.size());

        System.out.println("Current biggest prime: " + primeArray.get(primeArray.size() - 1));
        System.out.println("Prime needed to accurate calculate primes about Long.MaxValue: " + (long) Math.sqrt(Long.MAX_VALUE));
        System.out.println("Looking for other prime numbers starting from:");
        BigDecimal n = new BigDecimal(Long.MAX_VALUE).add(new BigDecimal(2));
        System.out.println(n);

        time.start();
        for (int primeCount = 0; primeCount < 5; n = n.add(new BigDecimal(2))) {

            if (time.nextFiveSeconds()) {
                System.out.println("Primes above Long.Max found: " + primeCount);
                System.out.println("Current biggest prime: " + primeArray.get(primeArray.size() - 1));

                System.out.println("Currently checking if " + n + " is prime.");
            }
            if (isPrime(sqrt(n).longValue())) {
                primeCount++;
            }

        }

        System.out.println("DONE. Found 5 primes...");


    }

    public static boolean isPrime2(long n) {

        long square = (long) Math.sqrt(n);
        for (int i = 2; i <= square; i++) {

            if (n % i == 0) {
                return false;
            }
        }

        return true;
    }

    public static BigDecimal getMersennePrime(int p) {

        return new BigDecimal(2).pow(p).subtract(BigDecimal.ONE);
    }

    private static boolean isPrime(long n) {


        for (long i : primeArray) {

            if (n % i == 0) {
                return false;
            }
            if (i > n) {
                break;
            }
        }

        for (long i = primeArray.get(primeArray.size() - 1); i < n; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }

        primeArray.add(n);
        return true;
    }


    // Karp's Tricks, this can be implemented without a loop in only two lines, giving 32 digits precision
    private static BigDecimal sqrt(BigDecimal value) {
        BigDecimal x = new BigDecimal(Math.sqrt(value.doubleValue()));
        return x.add(new BigDecimal(value.subtract(x.multiply(x)).doubleValue() / (x.doubleValue() * 2.0)));
    }

}

Wednesday 21 September 2016

Chapter 10 Exercise 17, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

Chapter 10 Exercise 17:

10.17 (Square numbers)
Find the first ten square numbers that are greater than Long.MAX_VALUE.
A square number is a number in the form of n2. For example, 4, 9, and 16
are square numbers. Find an efficient approach to run your program fast.

import java.math.BigDecimal;

public class Exercise_17 {

    public static void main(String[] args) {

        BigDecimal longMaxValue = new BigDecimal(Long.MAX_VALUE);
        long start = (long) Math.sqrt(Long.MAX_VALUE);
        BigDecimal n = new BigDecimal(start);
        int count = 0;


        while (count < 10) {

            BigDecimal squared = n.multiply(n);
            if (squared.compareTo(longMaxValue) > 0) {
                count++;
                System.out.println(count+": " + n + " squared = " + squared);
            }
            n = n.add(BigDecimal.ONE);
        }
    }

}

Chapter 10 Exercise 16, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

Chapter 10 Exercise 16:

10.16 (Divisible by 2 or 3) Find the first ten numbers with 50 decimal digits that are divisible by 2 or 3

import java.math.BigDecimal;
public class Exercise_16 {

    public static void main(String[] args) {

        String numString = "" + 1;
        // creating a 50 digit decimal number
        for (int i = 0; i < 49; i++) {

            numString += "0";
        }

        BigDecimal hugeNum = new BigDecimal(numString);
        int hugeNumCount = 0;
        while (hugeNumCount < 10) {

            // check if huge number if divisible by 2 of 3
            BigDecimal remainder2 = hugeNum.remainder(new BigDecimal(2));
            BigDecimal remainder3 = hugeNum.remainder(new BigDecimal(3));
            if (remainder2.equals(BigDecimal.ZERO) || remainder3.equals(BigDecimal.ZERO)) {
                hugeNumCount++;
                System.out.println(hugeNumCount +": " + hugeNum);
            }
            hugeNum = hugeNum.add(BigDecimal.ONE);
        }
    }
}

Chapter 10 Exercise 15, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

Chapter 10 Exercise 15:
"*10.15 (Geometry: the bounding rectangle)
A bounding rectangle is the minimum rectangle that encloses a set of points in a two-dimensional
plane, as shown in Figure 10.24d. Write a method that returns a bounding rectangle for a set of
points in a two-dimensional plane, as follows:"
 *
"public  static  MyRectangle2D  getRectangle(double[][]  points)"
"The Rectangle2D class is defined in Programming Exercise 10.13. Write a"
"test program that prompts the user to enter five points and displays the bounding
rectangle’s center, width, and height. Here is a sample run:"
 *
"Enter five points: 1.0 2.5 3 4 5 6 7 8 9 10"
"The bounding rectangle's center (5.0, 6.25), width 8.0, height 7.5"

import javafx.scene.shape.Rectangle;
public class MyRectangle2D extends GeometricObject {

    private static final int X = 0;
    private static final int Y = 1;

    public double centerX;
    public double centerY;

    public double width;
    public double height;

    public MyRectangle2D(double centerX, double centerY, double width, double height) {
        this.centerX = centerX;
        this.centerY = centerY;
        this.width = width;
        this.height = height;
    }

    public MyRectangle2D(MyPoint centerPoint, double width, double height) {
        this(centerPoint.x, centerPoint.y, width, height);
    }

    public MyRectangle2D(Rectangle rectangle) {
        this(rectangle.getX(), rectangle.getY(), rectangle.getWidth(), rectangle.getHeight());
    }

    public MyRectangle2D() {
        this(0, 0, 1, 1);
    }

    public MyPoint getCenterP() {
        return new MyPoint(centerX, centerY);
    }
    public MyPoint getP1() {
        return new MyPoint(centerX - width / 2, centerY + height / 2);
    }

    public MyPoint getP2() {
        return new MyPoint(centerX + width / 2, centerY + height / 2);
    }

    public MyPoint getP3() {
        return new MyPoint(centerX - width / 2, centerY - height / 2);
    }

    public MyPoint getP4() {
        return new MyPoint(centerX + width / 2, centerY - height / 2);
    }

    public double getCenterX() {
        return centerX;
    }

    public void setCenterX(double centerX) {
        this.centerX = centerX;
    }

    public double getCenterY() {
        return centerY;
    }

    public void setCenterY(double centerY) {
        this.centerY = centerY;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    /** returns the perimeter of the rectangle. **/
    @Override
    public double getPerimeter() {

        return width * 2 + height * 2;
    }

    /** returns the area of the rectangle **/
    @Override
    public double getArea() {
        return width * height;
    }

    public boolean contains(double x, double y) {

        // Get max X & Y
        double maxX = getMax(getP1().x, getP2().x, getP3().x, getP4().x);
        double maxY = getMax(getP1().y, getP2().y, getP3().y, getP4().y);
        // Get min X & Y
        double minX = getMin(getP1().x, getP2().x, getP3().x, getP4().x);
        double minY = getMin(getP1().y, getP2().y, getP3().y, getP4().y);

        if (x < minX || x > maxX || y < minY || y > maxY)  return false;

        return true;

    }

    public boolean contains(MyRectangle2D r2) {
        double xDistance = (r2.centerX > centerX) ? r2.centerX - centerX : centerX - r2.centerX;
        double yDistance = (r2.centerY > centerY) ? r2.centerY - centerY : centerY - r2.centerY;

        // if the r2 is inside this rectangle
        // this is only valid if the rectangles are parallel
        return (xDistance <= (width - r2.width) / 2 && yDistance <= (height - r2.height) / 2);

    }

    public boolean overlaps(MyRectangle2D r2) {
        // subtract from the highest number
        double xDistance = (r2.centerX > centerX) ? r2.centerX - centerX : centerX - r2.centerX;
        double yDistance = (r2.centerY > centerY) ? r2.centerY - centerY : centerY - r2.centerY;

        // if the r2 overlaps this rectangle
        // this is only valid if the rectangles are parallel
        return (xDistance <= (width + r2.width) / 2 && yDistance <= (height + r2.height) / 2);

    }

    public static boolean r1OverLapsR2(Rectangle r1, Rectangle r2) {
        return r1.intersects(r2.getBoundsInLocal()) || r2.intersects(r1.getBoundsInLocal());
    }

    public javafx.scene.shape.Rectangle getRectangle() {
        return new Rectangle(centerX, centerY, width, height);
    }
    public boolean contains(MyPoint[] points) {

        for (MyPoint p : points) {
            if (!contains(p)) return false;
        }
        return true;
    }

    public boolean contains(MyPoint point) {
        return contains(point.x, point.y);
    }

    public static MyRectangle2D getRectangle(double[][] points) {

        // find leftLowestPoint

        // find rightMostPoint

        // find the center from highest and lowest point

        // x distance = width

        // y distance = height
        MyPoint[] myPoints = new MyPoint[points.length];
        for (int i = 0; i < points.length; i++) {
            myPoints[i] = new MyPoint(points[i][0], points[i][1]);
        }

        return getRectangle(myPoints);
    }

    public static MyRectangle2D getRectangle(MyPoint[] points) {

        MyPoint leftMost = getLeftMostPoint(points);
        MyPoint rightMost = getRighMostPoint(points);
        double width = Math.abs(rightMost.x - leftMost.x);

        MyPoint highest = getHighestPoint(points);
        MyPoint lowest = getLowestPoint(points);
        double height = Math.abs(highest.y - lowest.y);

        double centerX = highest.getCenterPoint(lowest).x;
        double centerY = leftMost.getCenterPoint(rightMost).y;

        return new MyRectangle2D(centerX, centerY, width, height);
    }

    private static MyPoint getLeftMostPoint(MyPoint[] points) {

        MyPoint leftMost = points[0];
        for (int i = 0; i < points.length; i++) {
            if (leftMost.x > points[i].x) {
                leftMost = points[i];
            }
        }
        return leftMost;
    }

    private static MyPoint getRighMostPoint(MyPoint[] points) {

        MyPoint rightMost = points[0];
        for (int i = 0; i < points.length; i++) {
            if (rightMost.x < points[i].x) {
                rightMost = points[i];
            }
        }
        return rightMost;
    }

    private static MyPoint getHighestPoint(MyPoint[] points) {

        MyPoint highest = points[0];
        for (int i = 0; i < points.length; i++) {
            if (highest.y < points[i].y) {
                highest = points[i];
            }
        }
        return highest;
    }

    private static MyPoint getLowestPoint(MyPoint[] points) {

        MyPoint lowest = points[0];
        for (int i = 0; i < points.length; i++) {
            if (lowest.y > points[i].y) {
                lowest = points[i];
            }
        }
        return lowest;
    }

    private double getMax(double... n) {
        double max = n[0];
        for (int i = 1; i < n.length; i++) {
            if (max < n[i]) {
                max = n[i];
            }
        }
        return max;
    }
    private double getMin(double... n) {
        double min = n[0];
        for (int i = 1; i < n.length; i++) {
            if (min > n[i]) {
                min = n[i];
            }
        }
        return min;
    }

    @Override
    public String toString() {
        return "MyRectangle2D{" +
                "centerX=" + centerX +
                ", centerY=" + centerY +
                ", width=" + width +
                ", height=" + height +
                '}';
    }
}

import java.util.Scanner;
public class Exercise_15 {

    public static void main(String[] args) {

        // 1.0 2.5 3 4 5 6 7 8 9 10
        System.out.print("Enter 5 given points: ");
        Scanner input = new Scanner(System.in);
        double[][] points = new double[5][2];
        for (int i = 0; i < points.length; i++) {
            points[i][0] = input.nextDouble();
            points[i][1] = input.nextDouble();
        }

        MyRectangle2D r1 = MyRectangle2D.getRectangle(points);
        System.out.println("Center point: " + r1.getCenterP().toString());
        System.out.println("width = " + r1.getWidth());
        System.out.println("height = " + r1.getHeight());
    }
}