Given the dimensions of a flat rectangular piece of paper (paper_width x paper_height) and the dimensions of a target rectangular shape (target_width x target_height), determine the minimum number of folds required to reduce the paper to the target shape.
Each fold halves exactly one dimension of the paper (either the width or the height). The paper can be oriented in either direction, meaning you may match the paper's width to the target's height and vice versa.
If it is impossible to reach the target shape through any sequence of folds, return -1.
Function Signature
def min_folds(paper_width: int, paper_height: int, target_width: int, target_height: int) -> int:
Rules
-
A fold replaces one side length
d
with exactly
d / 2
. Lengths are never rounded, so folding a side of odd length gives a fractional length.
-
The paper matches the target when its two side lengths equal
target_width
and
target_height
in either order. Turning the paper over or around does not count as a fold.
-
Return
0
when the paper already matches the target, and
-1
when no sequence of folds produces it.
Constraints
-
1 <= paper_width, paper_height <= 10^9
-
1 <= target_width, target_height <= 10^9
Examples
Input: paper_width = 8, paper_height = 4, target_width = 2, target_height = 2
Output: 3
Folding the width twice takes it from 8 to 4 to 2, and folding the height once takes it from 4 to 2, for 3 folds in total.
Input: paper_width = 16, paper_height = 8, target_width = 4, target_height = 2
Output: 4
Folding the width from 16 to 8 to 4 and the height from 8 to 4 to 2 takes 4 folds. Matching the other way round (16 down to 2 and 8 down to 4) also takes 4.
Input: paper_width = 3, paper_height = 20, target_width = 5, target_height = 3
Output: 2
The side of length 3 can never become 5, so the paper has to be turned. Its 3 side then matches the target height with no folds, and its 20 side folds from 20 to 10 to 5.