# hdu5656 dp

CA Loves GCD

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.

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

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

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int buf[1010][1010];
int num[1010];
int dp[1010][1010];
int mod = 100000007;
int gcd(int a, int b) {  //记忆化gcd，否则容易超时
if (buf[a][b])return buf[a][b];
if (b == 0)return buf[a][b] = a;
return buf[a][b] = buf[b][a % b] = gcd(b, a % b);
}
int main()
{
int t;
scanf("%d",&t);
while (t--) {
int n;
scanf("%d",&n);
memset(dp, 0, sizeof(dp));
int Ma = 0;
for (int i = 1; i<=n; i++) {
scanf("%d",&num[i]);
Ma = max(Ma, num[i]);
}
for (int i = 1; i<=n; i++) {
dp[i][num[i]] = 1;
for (int j = 1; j<=Ma; j++) {
dp[i][j] += dp[i-1][j];
int t = gcd(num[i], j);
if(dp[i - 1][j])
dp[i][t] += dp[i-1][j];
dp[i][t] %= mod;
}
}
long long sum = 0;
for (int j = 1; j<=Ma; j++) {
sum += (long long)dp[n][j]*j;
sum %= mod;
}
printf("%lld\n",sum);
}
}

05-23 404

09-08 658
09-22 752
02-04 651
08-12 1357
03-10 976
07-13 618
08-21 606
07-08 652
11-19 691
04-01 3296
09-02 381
09-20 569
02-07
08-27 760
07-14 782
05-01 2386
08-24 26