Problem Description
CA is a fine comrade who loves the party and people; inevitably she loves GCD (greatest common divisor) too.
Now, there are N different numbers. Each time, CA will select several numbers (at least one), and find the GCD of these numbers. In order to have fun, CA will try every selection. After that, she wants to know the sum of all GCDs.
If and only if there is a number exists in a selection, but does not exist in another one, we think these two selections are different from each other.
Now, there are N different numbers. Each time, CA will select several numbers (at least one), and find the GCD of these numbers. In order to have fun, CA will try every selection. After that, she wants to know the sum of all GCDs.
If and only if there is a number exists in a selection, but does not exist in another one, we think these two selections are different from each other.
Input
First line contains
T
denoting the number of testcases.
T testcases follow. Each testcase contains a integer in the first time, denoting N , the number of the numbers CA have. The second line is N numbers.
We guarantee that all numbers in the test are in the range [1,1000].
1≤T≤50
T testcases follow. Each testcase contains a integer in the first time, denoting N , the number of the numbers CA have. The second line is N numbers.
We guarantee that all numbers in the test are in the range [1,1000].
1≤T≤50
Output
T
lines, each line prints the sum of GCDs mod
100000007
.
Sample Input
2 2 2 4 3 1 2 3
Sample Output
8 10
solution:
我们令dp[i][j]表示在前i个数中,选出若干个数使得它们的gcd为j的方案数,于是只需要枚举第i+1个数是否被选中来转移就可以了
令第i个数为v,当考虑dp[i][j]的时候,我们令dp[i][j] += dp[i-1][j];(v 不选),
dp[i][gcd(j,v)] +=dp[i-1][j](v 选)
tips:
由于long long的取模较耗时 因此我们可以用减法代替 注意此题mod=1e8+7!!!
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int inf = 100000007;
int dp[1001][1001], g[1001][1001];
int a[1001];
int gcd(int a, int b)
{
if (b == 0)return a;
return gcd(b, a%b);
}
int main()
{
int t, n;
for (int i = 1; i <= 1000; i++)
for (int j = 1; j <= 1000; j++)
g[i][j] = gcd(i, j);
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
memset(dp, 0, sizeof(dp));
long long ans = 0;
for (int i = 1; i <= n; i++)
{
dp[i][a[i]] = 1;
for (int j = 1; j <= 1000; j++)
{
dp[i][j]+=dp[i - 1][j];
if (dp[i][j] >= inf)dp[i][j] -= inf;
dp[i][g[j][a[i]]]+=dp[i - 1][j];
if (dp[i][g[j][a[i]]] >= inf)dp[i][g[j][a[i]]] -= inf;
}
}
for (int i = 1; i <= 1000; i++)
{
ans += 1ll * dp[n][i] * i;
ans%=inf;
}
printf("%I64d\n", ans);
}
return 0;
}