tc 2014 college tour 250 500

时间:2022-10-05 08:58:50

题意:

You are given a long long n. Return the largest divisor of n that is a perfect square. That is, the correct return value is x if and only if:

  1. x divides n
  2. There is an integer y such that x = y*y.
  3. x is the largest integer that satisfies conditions 1 and 2.

求最大的y*y 使N MOD (y*y)=0;

x = y*y 返回x的值。

分析:

假设 x*t = n;

当t<=10^6时,枚举t,同时查看是否符合y*y == x的条件。

当t>10^6时,即x<=10^12, y<=10^6, 此时枚举y,

所以两个10^6的循环就可以了。

500:  错误代码

 #include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <vector>
#include <algorithm>
#define LL long long
using namespace std; class SquareDivisor
{
public:
long long biggest(long long n)
{
long long i, x, tmp;
for(i = ; i <= ; i++)
{
if(n%i == )
{
x = n/i;
tmp = sqrt(x);
if(tmp*tmp == x)
return x;
}
}
for(i = ; i <= ; i++)
{
x = i*i;
if(n%x == )
return x;
}
}
}; int main()
{
long long n, ans;
SquareDivisor xx;
while(cin>>n)
{
ans = xx.biggest(n);
cout<<ans<<endl;
}
}

先保存一下,不知道为什么错了

知道错哪了:首先没有判断 x>n的时候停止, 而且第二个循环的时候从前向后 return 的不是最大值。

 #include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <vector>
#include <algorithm>
#define LL long long
using namespace std; class SquareDivisor
{
public:
long long biggest(long long n)
{
long long i, x, tmp;
for(i = ; i <= ; i++)
{
if(i > n) break; //
if(n%i == )
{
x = n/i;
tmp = sqrt(x);
if(tmp*tmp == x)
return x;
}
}
for(i = ; i >= ; i--) //
{
x = i*i;
if(x > n) continue; //
if(n%x == )
return x;
}
}
}; int main()
{
long long n, ans;
SquareDivisor xx;
while(cin>>n)
{
ans = xx.biggest(n);
cout<<ans<<endl;
}
}