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 for which and
Input
Input starts with an integer
denoting the number of test cases.
Each case starts with a line containing an integer
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
29
Sample 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
题意:给你一个数n,找出
使得
,其中
问有多少对这样的
思路:对于n我们可以写成
同理,i和j也可以写成这个形式
因为
所以
其中
当
的时候,
有
种情况
当
的时候,
有
种情况
一共有
种情况
但是
的情况出现了两次,所以我们要去重,去重后结果是
种情况
又因为
所以最终的结果
故
第一次做的时候没有打素数表,导致TLE一次…
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<map>
using namespace std;
typedef long long ll;
const int MAXN=1e7+9;
bool vis[MAXN];
int prime[1000000];
void getprime()
{
prime[0]=0;
for(int i=2;i<MAXN;i++)
{
if(!vis[i]) prime[++prime[0]]=i;
for(int j=2;j*i<MAXN;j++)
vis[i*j]=1;
}
}
int main()
{
int t;
int kase=0;
getprime();
scanf("%d",&t);
while(t--)
{
ll n;
ll ans=1;
scanf("%lld",&n);
for(ll i=1;(long long)prime[i]*prime[i]<=n&&i<prime[0];i++)
{
int cnt=0;
if(n%prime[i]==0)
{
while(n%prime[i]==0)
{
cnt++;
n/=prime[i];
}
ans*=2*cnt+1;
}
}
if(n!=1) ans*=2*1+1;
printf("Case %d: %lld\n",++kase,(ans+1)/2);
}
return 0;
}