Perfect Squares
Time limit1sMemory limit2048 MB
Given n up to 10^12, find three integers whose squares sum to n, or print -1 if no such triple exists by Legendre's three-square condition.
- Level
Medium5 of 10
- Topics
- Math, Number theory, Brute force
- Solved
- No attempts yet
Problem
A famous theorem in number theory states that every positive integer can be written as the sum of four perfect squares. Usually, though, fewer squares are enough. For example, needs only three perfect squares: .
A mathematician friend lists these facts about perfect squares:
- An odd prime is a sum of two squares if and only if .
- If two positive integers and are each a sum of two squares, then their product is also a sum of two squares.
- Every positive integer is a sum of three perfect squares, unless it has the form , where and are non-negative integers.
The last fact about sums of three squares interests you, so you decide to write a program that checks the claim and produces the actual squares.
Input
The input is a single integer ().
Output
If can be expressed as the sum of three squares, output three integers , , and . An answer is accepted if and . If several choices work, output any of them. Always print exactly three integers, even when is a sum of two or fewer squares. If cannot be expressed as the sum of three squares, output and nothing else.