Java Reference
In-Depth Information
that uses former function power that returns true if and only if this
equality is numerically satisfied (and false otherwise). Modify the main
function so that the user can also input the value of c interactively at
the console. When might this inequality fail in your program?
Exercise 3.3 (Binary representation)
Give a recursive function DisplayBase2 that takes as its argument a
non-negative number, and report its binary decomposition. For example,
the binary decomposition of the decimal number 11 is 1011: (11) 10 =
(1011) 2 . That is, we have the following unique decomposition: 11 =
1
2 0 . This binary decomposition can be
obtained by successively dividing by 2 and taking the remainder 0 or 1
each time.
Exercise 3.4 (Euclid's greatest common divisor)
2 3 +0
2 2 +1
2 1 +1
×
×
×
×
Use the property that GCD( a, b )=GCD( b, a mod b )andGCD( a, 0) =
|
for designing a recursive function static int GCD(int a, int b) .
One can use the function Math.abs(x) of the Math class to calculate the
absolute value of a given number x . Visualize the recursive function calls
by displaying the various function call parameters a and b . Illustrate
the recursive calls and the function call stack for a =15and b = 21.
Compare your code with the following one that uses a ternary operator:
a
|
Program 3.18 Euclid's greatest common divisor using recursion
static int gcd( int a, int b)
{ return (b!=0?gcd(b,a%b) :a);
}
Exercise 3.5 (Week day calendar)
The week day X of a given date given as M/D/Y (for month/day/year)
can be encoded as an integer X in range X
with Sunday
being encoded by 0. The week day is calculated by the following intricate
formula:
X = D +
∈{
0 , ..., 6
}
+ E + E
4
+ S
4
2 S
M
2 . 6
0 . 2
mod 7 ,
where
( M ,Y )= ( M
2 ,Y )
if M> 2 ,
( M +10 ,Y
1)
if M
2 .
and Y = 100 S + E with 0
100. Write a program that
takes as input a date formatted using the M/D/Y style and report
E
 
 
Search WWH ::




Custom Search