[蓝桥杯 2019 省 B] 等差数列

实际上这道题不需要先排序再求gcd,因为无论是哪两项之前作差,都不会影响最后的gcd的结果。

因为公差是从a2-a1开始算的,因此i=1时要特殊处理,不能把a1-0计入贡献,否则会算出错误的gcd。

即作差时不要加上a1-0,统计最值时不要漏掉a1

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <cmath>
#define For(i, j, n) for(int i = j ; i <= n ; ++i)
using namespace std;

const int N = 1e5 + 5;

int n, maxn = -1, minn = 1e9 + 1;

int gcd(int a, int b)
{
    return b?gcd(b, a % b):a;
}

int main()
{
    scanf("%d", &n);
    int x = 0, y = 0, new_d = 0, old_d = 0, ans = 0;
    scanf("%d", &y);
    maxn = max(maxn, y);
    minn = min(minn, y);
    for(int i = 2; i <= n; i++)
    {
        scanf("%d", &x);
        new_d = abs(x - y);
        y = x;
        ans = gcd(ans, gcd(old_d, new_d));
        old_d = new_d;
        maxn = max(maxn, x);
        minn = min(minn, x);
    }
    if(ans == 0)
        printf("%d\n", n);
    else
        printf("%d\n", (maxn - minn) / ans + 1);
    return 0;
}

 

posted @ 2024-03-09 20:43  Gold_stein  阅读(22)  评论(0编辑  收藏  举报