ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1593. Square Country. Version 2

Please, give some advices to solve this problem
Posted by ahmedov(NUUz_2) 23 Oct 2009 22:10
Thanks in advance
Achtung! Mathematical formulation of the solution here
Posted by melkiy 24 Oct 2009 02:19
1) If N==a^2, that is if N is a full square, the answer is 1

2) Try N = a^2 + b^2. Brute force, but "clever" brute force.
This is the most expensive part of the algo

3) N is NOT a sum of 3 squares <=> N=(8k+7)*4^m
This is a fast step, about O(log(N))

4) Lagrange theorem states: each number may be presented as a sum of 4 squares: N = a^2 + b^2 + c^2 + d^2
So if the upper three cases fails, the answer will be 4.
Re: Achtung! Mathematical formulation of the solution here
Posted by bsu.mmf.team 4 Apr 2010 21:43
Nice algorithm! Thank you, melkiy.
But you can find N = a^2 + b^2 without brute-force. I considered this case by facrotizing N to primes and using Ferma-Euler theorem.
Re: Achtung! Mathematical formulation of the solution here
Posted by cherudim 16 May 2011 12:30
How to apply Ferma-Euler theorem to this problem ?
Re: Achtung! Mathematical formulation of the solution here
Posted by luckysundog 8 Oct 2011 09:22
No brute force. Moreover, we don't need to find the sum of squares, we need just answer.

find factorization of N = L*m^2, where L is not divisible by p^2 for p is prime.
if L==1 then answer = 1
if L has no prime divisors of the form 4*t+3 then answer = 2 (Fermat)
if N != (8*t+7)*4^k then answer = 3 (Legendre)
else answer = 4
Re: Achtung! Mathematical formulation of the solution here
Posted by IgorKoval(from Pskov) 23 Jan 2012 17:16
Thank, every body.
+1
Re: Achtung! Mathematical formulation of the solution here
Posted by hatred [Ivanovo SPU] 19 Jan 2013 23:39
Got AC.

Edited by author 22.01.2013 20:14
Re: Achtung! Mathematical formulation of the solution here
Posted by neko13 7 Aug 2013 13:19
If L has prime divisors of the form 4*t+3,the answer may be 2,too.
How to explain this question?
Re: Achtung! Mathematical formulation of the solution here
Posted by balalaeshnik 20 Aug 2013 18:50
Fermat's theorem says that if N=a^2+b^2, then L hasn't prime divisors of the form 4t+3, and back.
Re: Achtung! Mathematical formulation of the solution here
Posted by evil_menace 30 Sep 2013 06:10
A simpler to calculate approach is just to check if the prime decomposition contains no ODD powers of primes that can be expressed as  4*t+3, in which case the answer is two.