Java Reference
In-Depth Information
numbers. The current Fibonacci number would then be
f0 + f1
. The algorithm
can be described as follows:
f0 =
0
;
// For fib(0)
f1 =
1
;
// For fib(1)
for
(
int
i =
1
; i <= n; i++) {
currentFib = f0 + f1;
f0 = f1;
f1 = currentFib;
}
// After the loop, currentFib is fib(n)
Write a test program that prompts the user to enter an index and displays its
Fibonacci number.
*18.3
(
Compute greatest common divisor using recursion
) The
gcd(m, n)
can also
be defined recursively as follows:
If
m % n
is
0
,
gcd(m, n)
is
n
.
■
Otherwise,
gcd(m, n)
is
gcd(n, m % n)
.
■
Write a recursive method to find the GCD. Write a test program that prompts the
user to enter two integers and displays their GCD.
18.4
(
Sum series
) Write a recursive method to compute the following series:
1
2
+
1
3
+ c +
1
i
m
(
i
)
=
1
+
Write a test program that displays
m(i)
for
i
=
1
,
2
, . . .,
10
.
18.5
(
Sum series
) Write a recursive method to compute the following series:
1
3
2
5
3
7
4
9
5
11
6
13
i
m
(
i
)
=
+
+
+
+
+
+ c +
2
i
+
1
Write a test program that displays
m(i)
for
i
=
1
,
2
, . . .,
10
.
*18.6
(
Sum series
) Write a recursive method to compute the following series:
1
2
2
3
i
m
(
i
)
=
+
+ c +
i
+
1
1
,
2
, . . .,
10
.
*18.7
(
Fibonacci series
) Modify Listing 18.2, ComputeFibonacci.java, so that the pro-
gram finds the number of times the
fib
method is called. (
Hint
: Use a static
variable and increment it every time the method is called.)
Section 18.4
*18.8
Write a test program that displays
m(i)
for
i
=
(
Print the digits in an integer reversely
) Write a recursive method that displays
an
int
value reversely on the console using the following header:
public static void
reverseDisplay(
int
value)
For example,
reverseDisplay(12345)
displays
54321
. Write a test program
that prompts the user to enter an integer and displays its reversal.
*18.9
(
Print the characters in a string reversely
) Write a recursive method that dis-
plays a string reversely on the console using the following header:
public static void
reverseDisplay(String value)
Search WWH ::
Custom Search