← all problems

booksToOverhang 🌶️🌶️🌶️

A stack of identical books sits on the edge of a table. In the best way to stack them, the top book sticks out past the one under it by 1/2 of a book length, the next book down by 1/4, the next by 1/6, and so on: the k-th book from the top sticks out 1/(2k) of a book length. The total overhang is all of these added up.

Write a method booksToOverhang that takes a Fraction target, the overhang you want in book lengths (from 0 up to 3/2), and returns the fewest books that give a total overhang of at least target. Add the overhangs with Fractions, starting from new Fraction(0, 1), and use getNumerator() and getDenominator() or toDouble() to compare.

For example, a target of 1/2 needs 1 book, a target of 3/4 needs 2 books (1/2 + 1/4), and a target of one whole book length needs 4.

Reference: Fraction — the methods you can call

class Fraction

A fraction of two ints, always kept in lowest terms with a positive denominator, so 2/4 and 1/2 are the same Fraction. A Fraction never changes once it is made. You do not write this class; make a fraction with new Fraction(numerator, denominator).

Fraction half = new Fraction(2, 4);
half.toString()                          // "1/2"
half.add(new Fraction(1, 3)).toString()  // "5/6"
half.getDenominator()                    // 2
half.toDouble()                          // 0.5
half.equals(new Fraction(1, 2))          // true
MethodWhat it does
Fraction(int numerator, int denominator)

Makes a fraction, reduced to lowest terms. A negative denominator moves its sign to the numerator. A denominator of 0 stops the program with an error.

  • numerator – the top number
  • denominator – the bottom number, not 0
int getNumerator()

The top number, after reducing.

Returns the numerator

int getDenominator()

The bottom number, after reducing; never negative.

Returns the denominator

double toDouble()

The value of the fraction as a decimal.

Returns numerator divided by denominator, as a double

Fraction add(Fraction other)

The sum of this fraction and another, as a NEW Fraction in lowest terms. Neither original changes.

  • other – the fraction to add

Returns the sum

boolean equals(Fraction other)

Whether another fraction has the same value (the same numerator and denominator once reduced).

  • other – the fraction to compare with

Returns true if equal; false otherwise, including for null

String toString()

The fraction as text, "numerator/denominator", for example "1/2".

Returns the fraction as text