UVA 1426 - Discrete Square Roots

枚舉N的因子 

合併模線性方程   

暴力找答案


/*
 * test.cpp
 *
 *  Created on: 2013-7-3
 *      Author: Administrator
 */
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
#include <cmath>
using namespace std;
const int maxn = 20;
typedef long long LL;
template<typename T>
T gcd(T a, T b) {
	return b ? gcd(b, a % b) : a;
}
template<typename T>
T lcm(T a, T b) {
	return a / gcd(a, b) * b;
}
template<typename T>
T exgcd(T a, T b, T &x, T &y) {
	if (b == 0) {
		x = 1;
		y = 0;
		return a;
	}
	T d = exgcd(b, a % b, x, y);
	T t = x;
	x = y;
	y = t - (a / b) * y;
	return d;
}
LL ans[14111], sz;
void solve(LL X, LL N, LL r) {
	int i, j;
	LL p, q;
	LL x, y, c, d, t, m;
	sz = 0;
	for (i = 1; 1LL * i * i <= N; ++i) {
		if (N % i == 0) {
			p = i;
			q = N / i;
			m = lcm(p, q);

			d = exgcd(p, q, x, y);
			c = 2 * r;
			LL b = q / d;
			if (c % d == 0) {
				x *= c / d;
				x = (x % b + b) % b;
				t = x * p - r;
				for (j = 0; t < N; t += m, ++j) {
					if (t >= 0 && t * t % N == X) {
						ans[sz++] = t, ans[sz++] = N - t;
					}
				}
			}

			swap(p, q);
			c = 2 * r;
			d = exgcd(p, q, x, y);
			b = q / d;
			if (c % d == 0) {
				x *= c / d;
				x = (x % b + b) % b;
				t = x * p - r;
				for (j = 0; t < N; t += m, ++j) {
					if (t >= 0 && t * t % N == X) {
						ans[sz++] = t, ans[sz++] = N - t;
					}
				}
			}
		}

	}

	sort(ans, ans + sz);
	sz = unique(ans, ans + sz) - ans;
	for (i = 0; i < sz; ++i)
		cout << " " << ans[i];
	cout << endl;
}
void check(int N, int X) {
	for (int i = 1; i < N; ++i) {
		//cout<<i<<" "<<i*i%N<<endl;
		if (1LL * i * i % N == X) {

			cout << i << " ";
		}
	}
	cout << endl;
}
int main() {
	ios::sync_with_stdio(false);
	int X, N, r;
	for (int cas = 1;; ++cas) {
		cin >> X >> N >> r;
		if (!(X | N | r))
			break;
		cout << "Case " << cas << ":";
		//check(N, X);
		solve(X, N, r);
	}
	return 0;
}


發佈了102 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章