CSC231 Homework 5 Solutions

From dftwiki3
Revision as of 11:50, 14 October 2012 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- =Problem #1= * Solution provided this week by Trevor and Sam: <code><pre> Trevor Haba and Sam Goodspeed 231a-ao 231a-am Problem 1 53: 20057446674355970889 ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 12:50, 14 October 2012 (EDT)



Problem #1

  • Solution provided this week by Trevor and Sam:
Trevor Haba  and  Sam Goodspeed
231a-ao		  231a-am

Problem 1

53: 20057446674355970889
54: 48422959787805316581
55: 116903366249966604050
56: 282229692287738524680
57: 681362750825443653409
58: 1644955193938625831497
59: 3971273138702695316402
60: 9587501471344016464300

Our java code:

package hw5;

//Hw5a.java
// Prints first terms of recursive series:
// F[1] = 1, F[2] = 1, F[n] = 2 * F[n-1] + F[n-2] - 1
// Stops when negative value comes up...
// To compile and run:
//    javac Hw5a.java
//    java Hw5a
//

import java.math.BigInteger;

class Hw5a {
    public static void main(String[] args ) {
	BigInteger Fn, Fn_1, Fn_2;
	int count;
	
	BigInteger b2 = new BigInteger("2");
	
	Fn_1 = BigInteger.ONE;
	Fn_2 = Fn_1;
	System.out.println( "F[1] = 1" );
	System.out.println( "F[2] = 1" );
 
	count = 2;
	while ( true ) {
	    Fn = Fn_1.multiply(b2).add(Fn_2).subtract(BigInteger.ONE);
	    Fn_2 = Fn_1;
	    Fn_1 = Fn;
	    count++;
	    if ( count >= 53 )
	    	System.out.println(count + ": " + Fn);
	    if (count > 60 )
	    	break;
	}
    }
 
}
  • Indeed one of the tricks was to use the BigInteger class of the Java Math library, if you were a java programmer. Using doubles was not adequate, as it only gives approximations of the numbers, not their exact values. Excel suffers from the same problem as it will use doubles which do not contain a sufficient number of bits to represent the numbers exactly.