Java Reference
In-Depth Information
**4.33
(
Perfect number
) A positive integer is called a
perfect number
if it is equal to the
sum of all of its positive divisors, excluding itself. For example, 6 is the first per-
fect number because
6 = 3 + 2 + 1
. The next is
28 = 14 + 7 + 4 + 2 +
1
. There are four perfect numbers less than 10,000. Write a program to find all
these four numbers.
***4.34
(
Game: scissor, rock, paper
) Exercise 3.17 gives a program that plays the scissor-
rock-paper game. Revise the program to let the user continuously play until
either the user or the computer wins more than two times.
*4.35
(
Summation
) Write a program to compute the following summation.
1
1
1
1
2
+
3
+
4
+
c
+
1
+ 2
2
2
+ 2
2
3
+ 2
2
624
+ 2
625
**4.36
(
Business application: checking ISBN
) Use loops to simplify Exercise 3.9.
**4.37
(
Decimal to binary
) Write a program that prompts the user to enter a decimal
integer and displays its corresponding binary value. Don't use Java's
Integer.toBinaryString(int)
in this program.
**4.38
(
Decimal to hex
) Write a program that prompts the user to enter a decimal inte-
ger and displays its corresponding hexadecimal value. Don't use Java's
Integer.toHexString(int)
in this program.
*4.39
(
Financial application: find the sales amount
) You have just started a sales job in
a department store. Your pay consists of a base salary and a commission. The
base salary is $5,000. The scheme shown below is used to determine the com-
mission rate.
Sales Amount
Commission Rate
$0.01-$5,000
8 percent
$5,000.01-$10,000
10 percent
$10,000.01 and above
12 percent
Your goal is to earn $30,000 a year. Write a program that finds out the minimum
number of sales you have to generate in order to make $30,000.
4.40
(
Simulation: heads or tails
) Write a program that simulates flipping a coin one
million times and displays the number of heads and tails.
**4.41
(
Occurrence of max numbers
) Write a program that reads integers, finds the
largest of them, and counts its occurrences. Assume that the input ends with
number
0
. Suppose that you entered
3 5 2 5 5 5 0
; the program finds that the
largest is
5
and the occurrence count for
5
is
4
.
(
Hint
: Maintain two variables,
max
and
count
.
max
stores the current max num-
ber, and
count
stores its occurrences. Initially, assign the first number to
max
and
1
to
count
. Compare each subsequent number with
max
. If the number is
greater than
max
, assign it to
max
and reset
count
to
1
. If the number is equal to
max
, increment
count
by
1
.)
3 5 2 5 5 5 0
Enter numbers:
The largest number is 5
The occurrence count of the largest number is 4