/** * CS151 Fall 2007 Lab #6 Solution
* Contains several static methods for practicing with loops. * * @author Scott Russell * @version 10/10/2007, last modified 10/12/2007 */ public class CSMath { /** * For a specified integer calculate the number of binary digits needed to store it. * @param value the integer to compute for * @return the number of binary digits needed. */ public static int numberOfBinaryDigits(int value) { //every number needs at least 1 binary digit int numberOfDigits = 1; //keep dividing by 2 and increasing numberOfDigits by 1 until result <= 1 while (value/2 >= 1) { value = value/2; numberOfDigits++; } return numberOfDigits; } /** * Compute and display a sequence of the Fibonacci numbers. * @param value the number of Fibonacci numbers to display. */ public static void displayFibonacciNumbers(int value) { int beforeLastNumber = 0; int lastNumber =1; int currentNumber = 0; //check to make sure should print first Fib. number if (value>=1) System.out.println(lastNumber); // now compute remaining Fib. numbers using sum of prior two and display it if (value >=2) for (int i =2; i<=value; i++) { currentNumber = beforeLastNumber + lastNumber; System.out.println(currentNumber); beforeLastNumber=lastNumber; lastNumber = currentNumber; } } /** * Compute and display all prime factors of a specified integer. * @param number the number to factor. */ public static void displayIntegerFactors(int value) { // boundary case is zero, just print it as its own factor if (value == 0) System.out.println(0); // if negative extract -1 and print remaining positive factors if (value < 0) { System.out.println(-1); displayIntegerFactors(value/-1); } else if (value > 1) { // check if two is a factor; if not keep adding one and trying until factor found int factor = 2; while (value % factor > 0) factor++; //print out the factor that was found System.out.println(factor); // factor the remainder of the original value // this technique is known as recursion displayIntegerFactors(value/factor); } } }