标签:actual 并且 cstring tar ast stack turn lin nbsp
Find the result of the following code:
long long pairsFormLCM( int n ) {
long long res = 0;
for( int i = 1; i <= n; i++ )
for( int j = i; j <= n; j++ )
if( lcm(i, j) == n ) res++; // lcm means least common multiple
return res;
}
A straight forward implementation of the code may time out. If you analyze the code, you will find that the code actually counts the number of pairs (i, j) for which lcm(i, j) = n and (i ≤ j).
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case starts with a line containing an integer n (1 ≤ n ≤ 1014).
For each case, print the case number and the value returned by the function ‘pairsFormLCM(n)‘
分析:题意1到n中存在多少对(a,b)满足lcm(a, b)==n。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn = 1e7+5;
int prim[maxn/10] ;
int k;
int vis[maxn];
void init() //线性筛
{
k = 0;
for(int i = 2; i < maxn; ++i)
{
if(!vis[i]) prim[k++] = i;
for(int j = 0; j < k && prim[j] * i < maxn; ++j)
{
vis[prim[j] * i] = 1;
if(i % prim[j] == 0) break;
}
}
}
int main(void)
{
int T, cas;
ll n;
scanf("%d", &T);
cas = 0;
init();
while(T--)
{
cas++;
scanf("%lld", &n);
ll ans = 1;
for(int i = 0; i < k; i++)
{
ll x = 0;
if((ll)(prim[i]) * prim[i] > n)
break;
while(n % prim[i] == 0)
{
x++;
n /= prim[i];
}
if(x)
ans *= 2 * x + 1;
}
if(n > 1)///n>1表示最后还剩一个素因子,比如6,20,并且这个素因子的平方大于n,再循环中没有处理。剩余最后一个因子按分析中的方法它对应三种取法,所以最后乘在ans上。
ans *= 3;
printf("Case %d: %lld\n", cas, ans / 2 + 1);
}
return 0;
}
标签:actual 并且 cstring tar ast stack turn lin nbsp
原文地址:http://www.cnblogs.com/dll6/p/7682852.html