51nod-1014 X^2 Mod P

1014 X^2 Mod P 

基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题

 收藏

 关注

X*X mod P = A,其中P为质数。给出P和A,求<=P的所有X。

Input

两个数P A,中间用空格隔开。(1 <= A < P <= 1000000, P为质数)

Output

输出符合条件的X,且0 <= X <= P,如果有多个,按照升序排列,中间用空格隔开。
如果没有符合条件的X,输出:No Solution

Input示例

13 3

Output示例

4 9

思路: 可以枚举也可以快速幂,我是用快速幂,加上TreeSet排序

import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class M1014 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		Set<Integer> set = new TreeSet<>();
		int P = in.nextInt();
		int A = in.nextInt();
		boolean isFind = false;
		for (int i = 1; i <= P; i++) {
			long num = i % P;
			long result = 1;
			num = (num*num)%P;
			if (P % 2 != 0) {
				result = (result*num)%P;
			}else {
				result = num;
			}
			if(result==A) {
				isFind = true;
				set.add(i);
			}	
		}

		if (!isFind) {
			System.out.println("No Solution");
		}else {
			for (Integer integer : set) {
				System.out.print(integer+" ");
			}
		}

	}

}

猜你喜欢

转载自blog.csdn.net/acDream_/article/details/81158019