C. Common Divisors
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a consisting of n integers.
Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.
For example, if the array a will be [2,4,6,2,10], then 1 and 2 divide each number from the array (so the answer for this test is 2).
Input
The first line of the input contains one integer n (1≤n≤4⋅105) — the number of elements in a.
The second line of the input contains n integers a1,a2,…,an (1≤ai≤1012), where ai is the i-th element of a.
Output
Print one integer — the number of such positive integers x such that x divides each number from the given array (in other words, the answer is the number of common divisors of all elements in the array).
Examples
input
5
1 2 3 4 5
output
1
input
6
6 90 12 18 30 18
output
4
題意: 給出一個數組,求滿足所有數組元素的共除數一共有多少個。
思路: 先找出所有數組元素的最大公約數,其數組元素的除數爲最大公約數的除數的個數,詳情看代碼和註釋。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 4e5 + 10;
ll a[N];
int main() {
int n;
scanf("%d", &n);
ll ans = 0;
// 先找出最大公約數,數組所有元素的共除數一定是最大公約數的除數數量
for (int i = 0; i < n; i++) {
scanf("%lld", &a[i]);
ans = __gcd(a[i], ans);
}
int cnt = 0;
// 計算最大公約數的除數數目
for (ll i = 1; i * i <= ans; i++) {
if (ans % i == 0) {
cnt++;
if (i * i != ans) cnt++;
}
}
printf("%d\n", cnt);
return 0;
}