Previous: 2.8 Exercises
Up: 2 Basic Concepts
Previous Page: 2.8 Exercises
We will use two variables, prev1 and prev2, such that prev1 is the last fibonacci number and prev2 is the one before the last. Print the first two fibonacci numbers, 1 and 1; and initialize prev1 and prev2 as 1 and 1. The new fib_number is the sum of the two previous numbers, prev1 and prev2; the new fib_number is now the last fibonacci number and prev1 is the one before the last. So, save prev1 in prev2 and save fib_number in prev1. Repeat the process while fib_number is less than 100.
Initialize a variable to 1. Multiply by 2 and add 1 to the variable repeatedly until a negative value appears in the variable. The value of the variable just before it turned negative is the largest positive value.
The above follows from the fact that multiplying by 2 shifts the binary form to the left by one position. Adding one to the result makes all ones in the less significant part and all zeros in the more significant part. Eventually a 1 appears in the leading sign bit, i.e. a negative number appears. The result just before that happens is the one with all ones except for the sign bit which is 0. This is the largest positive value.