tc 2014 college tour 250 500
题意:
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:
- x divides n
- There is an integer y such that x = y*y.
- 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: 错误代码
1 #include <iostream> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cmath> 5 #include <cstdio> 6 #include <vector> 7 #include <algorithm> 8 #define LL long long 9 using namespace std; 10 11 class SquareDivisor 12 { 13 public: 14 long long biggest(long long n) 15 { 16 long long i, x, tmp; 17 for(i = 1; i <= 1000000; i++) 18 { 19 if(n%i == 0) 20 { 21 x = n/i; 22 tmp = sqrt(x); 23 if(tmp*tmp == x) 24 return x; 25 } 26 } 27 for(i = 1; i <= 1000000; i++) 28 { 29 x = i*i; 30 if(n%x == 0) 31 return x; 32 } 33 } 34 }; 35 36 int main() 37 { 38 long long n, ans; 39 SquareDivisor xx; 40 while(cin>>n) 41 { 42 ans = xx.biggest(n); 43 cout<<ans<<endl; 44 } 45 }
先保存一下,不知道为什么错了
知道错哪了:首先没有判断 x>n的时候停止, 而且第二个循环的时候从前向后 return 的不是最大值。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cmath> 5 #include <cstdio> 6 #include <vector> 7 #include <algorithm> 8 #define LL long long 9 using namespace std; 10 11 class SquareDivisor 12 { 13 public: 14 long long biggest(long long n) 15 { 16 long long i, x, tmp; 17 for(i = 1; i <= 1000000; i++) 18 { 19 if(i > n) break; // 20 if(n%i == 0) 21 { 22 x = n/i; 23 tmp = sqrt(x); 24 if(tmp*tmp == x) 25 return x; 26 } 27 } 28 for(i = 1000000; i >= 1; i--) // 29 { 30 x = i*i; 31 if(x > n) continue; // 32 if(n%x == 0) 33 return x; 34 } 35 } 36 }; 37 38 int main() 39 { 40 long long n, ans; 41 SquareDivisor xx; 42 while(cin>>n) 43 { 44 ans = xx.biggest(n); 45 cout<<ans<<endl; 46 } 47 }