AP Computer Science I

advertisement
AP Computer Science I
Lab Assignment # 05_02
Three Initials Fun With Math Program
Assignment Purpose: Demonstrate knowledge of selection and repetition control structures.
Part 1 of this lab- Using a post condition loop, present a menu to the user:
1. Compute Factorial
2. Fibonacci Sequence
3. GCF
4. Extra Credit – LCM
5. Quit
Part 2
User enters a value, compute factorial of the value, display
Part 3
User enters number of terms. The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, …
It is formed by starting with 0 and 1 and then adding the latest two numbers to get the next one:
0 1 --the series starts like this.
0+1=1 so the series is now
0 1 1
1+1=2 so the series continues...
0 1 1 2 and the next term is
1+2=3 so we now have
0 1 1 2 3 and it continues as follows ...
Part 4 of this lab assignment involves using Euclid's Algorithm for computing the Greatest Common Factor
(GCF). This 2000-year-old algorithm is suited very well for the sequential instructions required by a computer
program. Euclid's Algorithm is shown below using 120 and 108 as sample numbers to compute the GCF of
12.
Algorithm Steps
Step 1:
Start with two integers
Step 2:
Divide Integer1 by Integer2 and compute the
remainder.
Step 3:
If the remainder equals 0, you are
finished. The GCF is Integer2.
Step 4:
If the remainder is not 0 then
Integer1 becomes Integer 2 and
Integer2 becomes the remainder
Step 5:
Go to Step2:
Step 2:
Divide Integer1 by Integer2 and compute the
remainder.
Step 3:
If the remainder equals 0, you are
finished. The GCF is Integer2.
Sample Problem
Integer1 is 120
Integer2 is 108
120 / 108 = 1
The remainder = 12
The remainder is not 0
You are not finished.
Integer1 is now 108
Integer2 is now 12
108 / 12 = 9
The remainder = 0
The remainder is 0
You are finished and the
GCF = 12
.
Extra Credit adds computing the Least Common Multiple (LCM) after the GCF is computed. The GCF makes computing
the LCM very easy. Start by using Euclid's algorithm to compute the GCF. Then use the following formula to compute the
LCM. Keep in mind that you must first compute an accurate GCF.
LCM = Number1 / GCF * Number2
Assume that Number1 = 120 and Number2 = 108. The earlier GCF explanation showed that the GCF of 120 and 108 =
12. With that information and the LCM formula we get the following result.
120 / 12 * 108 = 1080
Exposure Java Chapter VI Lab Assignment Page 1 08-03-04
Exposure Java Chapter VI Lab Assignment Page 2 08-03-04
Download