Sicily 2659. Number

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;
}                                 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值