Sum of Squares (More Huge)
Time limit0.5sMemory limit512 MB
Given n up to 10^18, print the minimum number of perfect squares (at most four) whose sum equals n.
- Level
Medium7 of 10
- Topics
- Math, Number theory, Binary search, Implementation
- Solved
- No attempts yet
Problem
In 1770, Lagrange proved that every natural number can be expressed as the 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 expressed as . Historically, the problem commonly given to mental calculation experts was to represent a natural number as a sum of four or fewer squares. In the early 1900s, one mental calculator was reported to have taken 8 seconds to find the solution . A harder problem took 56 seconds: .
Given a natural number , write a computer program that expresses as the sum of the fewest possible squares.
Input
Input comes from standard input. The input consists of one line containing a natural number , where .
Output
Output goes to standard output. Print, on one line, the minimum number of squares whose sum equals .