2659. Number
Constraints
Time Limit: 1 secs, Memory Limit: 256 MB
Description
Given an equation (a * x + b) % n = 0, where a,b,n are positive integers, please find out the least positive integer x make that equation holds.
Input
There are several test cases, one line for each case. For each line, there are three positive integers, all of which are no more than 2000000000. Input numbers have no leading zeros. There will be no more than 1000 test cases.
Input is ended with three 0.
Output
Output each result in one line. Output number must not have any leading zeros. If there is no positive integer makes the equation holds, then output -1.
Sample Input
1 1 1 1 1 2 1 1 3 3 4 5 5 1 5 0 0 0
Sample Output
1 1 2 2 -1
Problem Source
系列热身赛4@2011年上半学期算法考试和4+2选拔赛
// Problem#: 2659
// Submission#: 3593142
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <stdio.h>
long long extended_euclid(long long a, long long b, long long & x, long long & y) {
long long t, d;
if (b == 0) {
x = 1;
y = 0;
return a;
}
d = extended_euclid(b, a % b, x, y);
t = x;
x = y;
y = t - a / b * y;
return d;
}
long long modular_linear(long long a, long long b, long long n) {
long long d, x, y;
while (b < 0) b += n;
b %= n;
d = extended_euclid(a, n, x, y);
if (b % d) return -1;
else {
x *= b / d;
x = (x % (n / d) + n / d) % (n / d);
if (!x) x += n / d;
return x;
}
}
int main() {
long long a, b, n;
while (scanf("%lld%lld%lld", &a, &b, &n), a)
printf("%lld\n", modular_linear(a, -b, n));
return 0;
}