(* CS320 Fall 2006 Assignment 2, Problem 1. * Likai Liu, Computer Science Department, Boston University. * * Distribution without permission is prohibited and is a violation of U.S. * Copyright Law. Submitting this solution as your own work whether in part * or as a whole also violates Academic Code of Conduct. *) structure IntModulo = struct (* some modulo arithmetic operations for experimental purpose *) fun add_mod (n: int) (x: int, y: int): int = IntInf.toInt (IntInf.mod (IntInf.+ (IntInf.fromInt x, IntInf.fromInt y), IntInf.fromInt n)) fun sub_mod (n: int) (x: int, y: int): int = IntInf.toInt (IntInf.mod (IntInf.- (IntInf.fromInt x, IntInf.fromInt y), IntInf.fromInt n)) fun mul_mod (n: int) (x: int, y: int): int = IntInf.toInt (IntInf.mod (IntInf.* (IntInf.fromInt x, IntInf.fromInt y), IntInf.fromInt n)) (* ****** ****** *) val fromInt = Int.fromInt val op+ = add_mod 1000000000 val op- = sub_mod 1000000000 val op* = mul_mod 1000000000 end (* change the following line to * structure I = IntInf * to see all digits beyond the first 9. *) structure I = IntModulo local open I in type mat22_t = int * int * int * int type vec2_t = int * int val zero = fromInt 0 val one = fromInt 1 val id = (one, zero, zero, one) fun m22_mul_m22 (((a11, a12, a21, a22): mat22_t), ((b11, b12, b21, b22): mat22_t)): mat22_t = (a11 * b11 + a12 * b21, a11 * b12 + a12 * b22, a21 * b11 + a22 * b21, a21 * b12 + a22 * b22) fun m22_mul_v2 (((a11, a12, a21, a22): mat22_t), ((b1, b2): vec2_t)): vec2_t = (a11 * b1 + a12 * b2, a21 * b1 + a22 * b2) end fun m22_pow (x: mat22_t, n: int): mat22_t = let fun loop (x, n, res) = if n = 0 then res else if n mod 2 = 0 then loop (m22_mul_m22 (x, x), n div 2, res) else loop (m22_mul_m22 (x, x), n div 2, m22_mul_m22 (x, res)) in loop (x, n, id) end fun fib n = let val mat_a = (zero, one, one, one) val vec_init = (zero, one) val (b1, _) = m22_mul_v2 (m22_pow (mat_a, n), vec_init) in b1 end