1 /*
   2  * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
   3  *
   4  * Redistribution and use in source and binary forms, with or without
   5  * modification, are permitted provided that the following conditions
   6  * are met:
   7  *
   8  *   - Redistributions of source code must retain the above copyright
   9  *     notice, this list of conditions and the following disclaimer.
  10  *
  11  *   - Redistributions in binary form must reproduce the above copyright
  12  *     notice, this list of conditions and the following disclaimer in the
  13  *     documentation and/or other materials provided with the distribution.
  14  *
  15  *   - Neither the name of Oracle nor the names of its
  16  *     contributors may be used to endorse or promote products derived
  17  *     from this software without specific prior written permission.
  18  *
  19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  20  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  21  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30  */
  31 
  32 /*
  33  * This source code is provided to illustrate the usage of a given feature
  34  * or technique and has been deliberately simplified. Additional steps
  35  * required for a production-quality application, such as security checks,
  36  * input validation and proper error handling, might not be present in
  37  * this sample code.
  38  */
  39 package stream.parallel;
  40 
  41 import java.util.stream.Stream;
  42 
  43 /**
  44  * This demo shows how to use the parallel calculation to calculate Fibonacci
  45  * sequence. This is a 2-dimensional system of linear difference equations that
  46  * describes the Fibonacci sequence.
  47  *
  48  * @author tyan
  49  */
  50 public class Fibonacci {
  51     /**
  52      * First Fibonacci number.
  53     */
  54     private final static long FIBONACCI_1 = 1;
  55 
  56     /**
  57      * Second Fibonacci number.
  58     */
  59     private final static long FIBONACCI_2 = 1;
  60 
  61     /**
  62      * A base matrix that will be used to calculate Fibonacci sequence.
  63      */
  64     private final static long[][] BASE
  65             = new long[][]{
  66                 {FIBONACCI_2, FIBONACCI_1},
  67                 {FIBONACCI_1, 0}
  68               } ;
  69 
  70     /**
  71      * @param args argument to run program
  72      */
  73     public static void main(String[] args) {
  74         try {
  75             if (args.length != 1) {
  76                 throw new Exception("Only accept one argument");
  77             }
  78             int position = Integer.parseInt(args[0]);
  79             if (position < 3) {
  80                 throw new Exception("Postiion must be greater than 3");
  81             }
  82             System.out.printf("The %dth fibonacci number is %d\n" , position,
  83                     power(BASE, position)[0][1]);
  84         } catch (Exception nfe) {
  85             usage();
  86         }
  87     }
  88 
  89     /**
  90      * Matrix binaries operation multiplication.
  91      * @param matrix1 matrix to be multiplied.
  92      * @param matrix2 matrix to multiply.
  93      * @return A new generated matrix which has same number of rows as matrix1
  94      * and same number of columns as matrix2.
  95      */
  96     private static long[][] times(long[][] matrix1, long[][] matrix2) {
  97         long[][] result = new long[2][2];
  98         for(int row = 0; row < matrix1.length; row++) {
  99             for(int col =0; col < matrix2[row].length; col++) {
 100                 for(int col1 =0; col1 < matrix1[row].length; col1++) {
 101                     result[row][col] += matrix1[row][col1] * matrix2[col1][col];
 102                 }
 103             }
 104         }
 105         return result;
 106     }
 107 
 108     /**
 109      * Power operation to matrix. Requirement for power operation is matrix must
 110      * have same number row and column.
 111      * @param matrix base
 112      * @param n      the exponent
 113      * @return the value of the first argument raised to the power of the second
 114      * argument.
 115      */
 116     private static long[][] power(long[][] matrix, int n) {
 117         return Stream.generate(() -> matrix).
 118                 limit(n).
 119                 reduce(Fibonacci::times).
 120                 get();
 121     }
 122 
 123     /**
 124      * Usage of this program
 125      */
 126     public static void usage() {
 127         System.out.println("Usage: java Fibonacci Position");
 128         System.out.println("Postiion must be a integer greater than 3");
 129     }
 130 }