All Tracks Math Number Theory Problem

Monk and Square Root
Tag(s):

Easy, Math, approved

Problem
Editorial
Analytics

Given two integers $$N$$ and $$M$$, help Monk find an integer $$X$$, such that $$X^2 \; \% \; M = N$$ and $$0 \le X$$. If there are multiple values of $$X$$ print smallest one. If there is no possible value of $$X$$ print $$-1$$.

Note: Make sure you handle integer overflow.

Input:
First line consists of a single integer $$T$$ denoting the number of test cases.
Each test case consists of a single line containing two space separated integers denoting $$N$$ and $$M$$.

Output:
For each test case print the required answer.

Constraints:
$$1 \le T \le 100$$
$$0 \le N \lt M \le 10^6$$

SAMPLE INPUT
2
4 5
0 4
SAMPLE OUTPUT
2
0
Explanation

$$2$$ is the smallest positive integer such that $$(2 \times 2) \; \% 5 = 4$$

Time Limit: 1.0 sec(s) for each input file.
Memory Limit: 256 MB
Source Limit: 1024 KB
Marking Scheme: Marks are awarded when all the testcases pass.
Allowed Languages: C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, Haskell, Java, Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Lisp, Lisp (SBCL), Lua, Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, Python 3, R(RScript), Racket, Ruby, Rust, Scala, Swift, Visual Basic, Kotlin

CODE EDITOR

Initializing Code Editor...
Your Rating:

Contributor

This Problem was Asked in

HackerEarth

Challenge Name

CodeMonk (Number Theory Part I)

OTHER PROBLEMS OF THIS CHALLENGE
Notifications
View All Notifications