Given an integer N,you should come up with the minimum nonnegative integer M.M meets the follow condition: M 2%10 x=N (x=0,1,2,3....)
Input
The first line has an integer T( T< = 1000), the number of test cases.
For each case, each line contains one integer N(0<= N <=10 9), indicating the given number.
Output
For each case output the answer if it exists, otherwise print “None”.
Sample Input
3 3 21 25
Sample Output
None 11 5
题意:M^2 % 10^x =N,求满足条件的最小的M
思路:可以根据余数N求出10^x的值
这样就相当于M的平方除以一个常数等于N
最直接的就是从0然后往上便利,这样肯定会超时的
所以就有思维在里边了--从i(0~9)可以先求出i*i的个位数等于N%10的数,放到优先队列中
只有相等的时候才可能才有可能满足题目的要求,然后这时候枚举
eg:N=21,num=N%10=1,mod=100,对于0~9,只有1和9的时候i*i才会出现1,所以入优先队列
然后开始枚举一位数,两位数三位数.......,比如11,21,31......;19,29........;
如果满足条件r.x*r.x%r.y==n%r.y,就可以入队了,直到找到一个数%mod==n就success了
import java.util.PriorityQueue;
import java.util.Scanner;
//按照x从小到大排序
class node implements Comparable<node>{
long x;
long y;
@Override
public int compareTo(node o) {
// TODO Auto-generated method stub
return (int) ((int)this.x-o.x);
}
}
public class Main {
static long mod;
static int n;
static PriorityQueue<node> q=new PriorityQueue<>();
public static void bfs(){
int num=n%10;
for(long i=0;i<10;i++){
if(i*i%10==num){
node s=new node();
s.x=i;
s.y=10;
q.offer(s);
}
}
boolean flag=false;
while(!q.isEmpty()){
node t=q.poll();
if(t.x*t.x%mod==n%mod){
System.out.println(t.x);
flag=true;
break;
}
for(int i=0;i<10;i++){
node r=new node();
r.x=t.x+i*t.y;//这里i是乘t.y,一开始乘以10了
r.y=t.y*10;
if(r.x*r.x%r.y==n%r.y){
q.offer(r);
}
}
}
if(!flag)
System.out.println("None");
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
while(t!=0){
n=scan.nextInt();
//先求出10^x的值
int nn=n;
mod=1;
while(nn!=0){
nn/=10;
mod*=10;
}
bfs();
t--;
}
}
}