返回题解分享
讨论 / 题解分享/ 帖子详情

等差数列(编程题) - 题解

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'

const int N = 1e5 + 10;

int n;
int a[N];

void solve()
{
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	sort(a + 1, a + 1 + n);

	int d = a[2] - a[1];
	if (d == 0)
	{
		cout << n << endl;
		return;
	}

	for (int i = 3; i <= n; i++)
		d = __gcd(d, a[i] - a[i - 1]); // 求所有差的最大公约数 

	cout << (a[n] - a[1]) / d + 1 << endl; // (an-a1)/d + 1求等差数列项数
}

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);

	solve();

	return 0;
}
0 回复 0 转发 0 喜欢 0 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!