Blue Bridge Zhenti: Arithmetic Sequence (Number Theory)

text

Topic description

The math teacher gave Xiao Ming a problem to sum arithmetic series. But the careless Xiao Ming forgot part of the sequence, and only remembered the N integers.
  Now given these N integers, Xiaoming wants to know how many terms are there in the shortest arithmetic sequence containing these N integers?

输入格式
  输入的第一行包含一个整数 N。
  第二行包含 N 个整数 A₁, A₂, · · · , AN。(注意 A₁ ∼ AN 并不一定是按等差数列中的顺序给出)
输出格式
  输出一个整数表示答案。
样例输入
5
2 6 4 10 20
样例输出
10
样例说明
  包含 2641020 的最短的等差数列是 2468101214161820

Topic ideas and codes

Idea: Given n numbers, which are part of an arithmetic sequence, how many minimum terms does the arithmetic sequence have? : ((the largest number - the smallest number) / d ) + 1 , where d is the greatest common factor of all the arithmetic sequence (the difference between all known numbers and the smallest number), and special consideration should be given if d = 0, is the n
code:

#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const ll maxn=1e6+10;
ll n;
ll a[maxn];
ll d[maxn];
ll gcd(ll a,ll b){
    
    
    return b?gcd(b,a%b):a;
}
int main(){
    
    
	cin>>n;
	for(int i=1;i<=n;i++){
    
    
		cin>>a[i];
	}
	sort(a+1,a+1+n);
	ll ans=a[2]-a[1];
    if(ans==0){
    
    
        cout<<n;
        return 0;
    }
    for(int i=3;i<=n;i++){
    
    
        ans=gcd((ll)(a[i]-a[i-1]),ans);
    }
    ll cnt=(a[n]-a[1])/ans+1;
    cout<<cnt;
	return 0;
}

Epilogue


"If you are undecided, you can ask the spring breeze, and if the spring breeze does not speak, you will follow your heart" means: if you are hesitant about something, ask the spring breeze how to do it. . "If you are undecided, you can ask the spring breeze. If the spring breeze does not speak, you will follow your heart." The sentence comes from the "Jianlai" written by the Internet writer "Fenghuo Opera Princes". The original text is: "If you are undecided, you can ask the spring breeze. Follow your heart".

insert image description here


Guess you like

Origin blog.csdn.net/weixin_46627433/article/details/123979099