Monk and Square Root

4

1 votes
Mathematics, Modular arithmetic
Problem

Given two integers N and M, help Monk find an integer X, such that X2%M=N and 0X. 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.

Video approach to solve this question: here

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:
1T100
0N<M106

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

2 is the smallest positive integer such that (2×2)%5=4

Editor Image

?