Problem Statement
Little Johnny has a stick that is 64 centimeters long, but he thinks it would be more fun to play with a stick that is x centimeters long. He decides to break the original stick into a number of smaller sticks, and then glue them together to get a stick that is exactly x centimeters long.
The easiest way to break a stick is to break it in half, so Johnny will use the following procedure:
- Sum the lengths of all the sticks (initially, there is just one 64 centimeter stick). While this sum is greater than x, repeat the following:
- Take one of the sticks with the shortest length and break it in half.
- If discarding one of the halves would not make the sum of the remaining sticks' lengths less than x, throw that half away.
- Finally, glue the remaining sticks together to form a stick that is x centimeters long.
Definition
- Class:
- Stick
- Method:
- pieces
- Parameters:
- int
- Returns:
- int
- Method signature:
- int pieces(int x)
- (be sure your method is public)
Notes
- The algorithm described in the problem statement guarantees that you will always end up with a total length of exactly x in the final step.
Constraints
- x will be between 1 and 64, inclusive.
Examples
32
Returns: 1
After the first break Johnny gets a stick 32cm long.
48
Returns: 2
First, he breaks the stick into two 32cm long sticks. Then, he breaks one of the 32cm sticks in half and discards one of the halves. The remaining two sticks have a total length of 48cm when glued together.
10
Returns: 2
1
Returns: 1
2
Returns: 1
3
Returns: 2
4
Returns: 1
5
Returns: 2
6
Returns: 2
7
Returns: 3
8
Returns: 1
9
Returns: 2
11
Returns: 3
12
Returns: 2
13
Returns: 3
14
Returns: 3
15
Returns: 4
16
Returns: 1
17
Returns: 2
18
Returns: 2
19
Returns: 3
20
Returns: 2
21
Returns: 3
22
Returns: 3
23
Returns: 4
24
Returns: 2
25
Returns: 3
26
Returns: 3
27
Returns: 4
28
Returns: 3
29
Returns: 4
30
Returns: 4
31
Returns: 5
33
Returns: 2
34
Returns: 2
35
Returns: 3
36
Returns: 2
37
Returns: 3
38
Returns: 3
39
Returns: 4
40
Returns: 2
41
Returns: 3
42
Returns: 3
43
Returns: 4
44
Returns: 3
45
Returns: 4
46
Returns: 4
47
Returns: 5
49
Returns: 3
50
Returns: 3
51
Returns: 4
52
Returns: 3
53
Returns: 4
54
Returns: 4
55
Returns: 5
56
Returns: 3
57
Returns: 4
58
Returns: 4
59
Returns: 5
60
Returns: 4
61
Returns: 5
62
Returns: 5
63
Returns: 6
64
Returns: 1