UVA10407 Simple division【同余+一阶差分】

Integer division between a dividend n and a divisor d yields a quotient q and a remainder r. q is the integer which maximizes q ∗ d such that q ∗ d ≤ n and r = n − q ∗ d.
    For any set of integers there is an integer d such that each of the given integers when divided by d leaves the same remainder.
在这里插入图片描述
Input
Each line of input contains a sequence of nonzero integer numbers separated by a space. The last number on each line is 0 and this number does not belong to the sequence. There will be at least 2 and no more than 1000 numbers in a sequence; not all numbers occuring in a sequence are equal. The last line of input contains a single 0 and this line should not be processed.
Output
For each line of input, output the largest integer which when divided into each of the input integers leaves the same remainder.
Sample Input
701 1059 1417 2312 0
14 23 17 32 122 0
14 -22 17 -31 -124 0
0
Sample Output
179
3
3

问题链接UVA10407 Simple division
问题简述:给定若干个整数(这些数不完全相同),求使这些数同余的最大除数。
问题分析:(略)
    先求差值,然后再做GCD运算。
    给出2个解法程序,不用数组存储的解法要好一些。
程序说明:(略)
参考链接:(略)
题记:不使用数组存储才是真功夫。

AC的C++语言程序如下:

/* UVA10407 Simple division */

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int a1, a;
    while(~scanf("%d", &a1) && a1) {
        int g = 0;
        while(scanf("%d", &a) == 1 && a) {
            int d = a - a1;
            if(d) {if(g) g = __gcd(g, d); else g = d;}
            a1 = a;
        }

        printf("%d\n", abs(g));
    }

    return 0;
}

AC的C++语言程序如下:

/* UVA10407 Simple division */

#include <bits/stdc++.h>

using namespace std;

const int N = 1000;
int d[N];

int main()
{
    int a1, a, cnt, k;
    while(~scanf("%d", &a1) && a1) {
        for(cnt = 0; scanf("%d", &a) == 1 && a; cnt++)
            d[cnt] = a - a1, a1 = a;
        for(k = 0; d[k] == 0; k++);
        int g = d[k++];
        for(; k < cnt; k++)
            if(d[k]) g = __gcd(g, d[k]);

        printf("%d\n", abs(g));
    }

    return 0;
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值