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 1132. Square Root

This can be solved without any deep math knowledge ! (and very fast)
Posted by Ostap Korkuna (Lviv NU) 14 Feb 2007 04:23
I've passed this problem with time 0.125 ! And the only mathematical conclusion I used is that when x is a square root then (n-x) is also.

I am sure that the mathematical approach to this problem is also interesting (and probably harder than mine) but it was still very interesting for me to find the way to solve this problem without using of deep math knowledge.
It is also interesting that my solution runs faster then some implementing the math approach :-) but still I use much  more memory...

http://acm.timus.ru/status.aspx?space=1&num=1132&author=30467

Thanks to mr. Medvedev for this problem.
I have used your idea,but I still TLE.Could you help me?
Posted by yessit 7 Mar 2007 18:23
program Ural_1132;
var
  i,j,x,p,q,n:longint;

function power(a,b,c:longint):longint;
var
  d,s:longint;
begin
  d:=a;s:=1;
  while b>0 do
  begin
    if odd(b) then s:=(s*d) mod c;
    b:=b div 2;d:=(d*d) mod c;
  end;
  exit(s);
end;

begin
  read(n);
  for i:=1 to n do
  begin
    read(q,p);q:=q mod p;
    if (p=2) and (q=1) or (p<>2) and (power(q,(p-1) div 2,p)=p-1) then
    begin
      writeln('No root');
      continue;
    end;
    if trunc(sqrt(q))=0 then
    begin
      x:=trunc(sqrt(q));
      write(x);
      if p-x<>x then write(' ',p-x);
      writeln;
      continue;
    end;
    for j:=1 to (p-1) div 2 do
    begin
      x:=(j*j) mod p;
      if x=q then
      begin
        write(j);
        if p-j<>j then write(' ',p-j);
        writeln;
        break;
      end;
    end;
  end;
end.

Edited by author 07.03.2007 18:27