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
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).
Output
For each case, print the case number and the value returned by the function pairsFormLCM(n).
Sample Input
15 2 3 4 6 8 10 12 15 18 20 21 24 25 27 29Sample Output
Case 1: 2 Case 2: 2 Case 3: 3 Case 4: 5 Case 5: 4 Case 6: 5 Case 7: 8 Case 8: 5 Case 9: 8 Case 10: 8 Case 11: 5 Case 12: 11 Case 13: 3 Case 14: 4 Case 15: 2
#include<iostream>
using namespace std;
#define ll long long
const int N=1e7+10;
ll n;
int t;
bool st[N];
int primes[N],cnt;
void get_prime(int n)
{
st[1]=true;
for(int i=2;i<=n;i++)
{
if(!st[i])primes[++cnt]=i;
for(int j=1;primes[j]<=n/i;j++)
{
st[primes[j]*i]=true;
if(i%primes[j]==0)break;
}
}
}
int main()
{
get_prime(N-9);
cin>>t;
int Case=0;
while(t)
{
int ans=1;
Case++;
t--;
cin>>n;
for(int i=1;i<cnt&&primes[i]<=n/primes[i];i++)
{
if(n%primes[i]==0)
{
int s=0;
while(n%primes[i]==0)n/=primes[i],s++;
ans*=((s+1)*2-1);
}
}
if(n>1)ans*=3;
ans/=2;
ans+=1;
cout<<"Case "<<Case<<": "<<ans<<'\n';
}
return 0;
}
增加通俗理解性;(这是对于个人理解,如果能帮助大家的话,乐意之至)
1,
18=(2^1)*(3^2);
那么对于要判断的i,j两个数,必须符合i和j当中的集合含有2^1和3^2这两个组合;(前后结合着理解)自己多带几个数试一下。
2,输入的n,在我们进行遍历时,只需便利到sqrt(n);即可;
3,对于 if(n>1)ans*=3; 的理解
这是因为当n=2,3时,由于sqrt(n)的原因无法进行便利,因此这里需要进行特判;