Four Squares
InterviewTime limit0.5sMemory limit512 MB
Given n up to 50,000, print the minimum number of perfect squares whose sum equals n.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Math, Brute force, Number theory
- Solved
- No attempts yet
Problem
In 1770 Lagrange proved that every natural number can be written as a sum of four or fewer squares. Some natural numbers have more than one such representation. For example, 26 is the sum of and ; it can also be written as . Historically, the problem commonly given to mental-calculation experts was to express a natural number as a sum of four or fewer squares. In the early 1900s, one mental calculator was reported to take 8 seconds to find the solution . A harder problem took 56 seconds: .
Given a natural number , write a program that expresses as a sum of squares using the minimum number of squares.
Input
Input comes from standard input. The input consists of one line containing the natural number , where .
Output
Output goes to standard output. Print, on one line, the minimum number of squares whose sum equals .