原题链接:https://www.aclass="superseo">cwing.com/problem/content/727/
由于时间复杂度限制,判断时判断遍历所有数会超时,只需要判断到根号a的情况即可(因为如果i是a的约数,那么a/i必是a的约数,那么只需要遍历到满足i<=a/i的情况,就可以得到最终结果),此时需要注意,如果a%i==0那么i是a的约数,a/i也是a的约数,如果i!=a/i的话,那么此时也需要把这个数加上
import math
while True:
try:
n = int(input())
for _ in range(n):
a = int(input())
sums = 0
for i in range(1,int(math.sqrt(a))+1):
if a%i==0:
if i<a:
sums+=i
if i!=a/i and a/i<a:
sums+=a/i
if sums==a:
print("{} is perfect".format(a))
else:
print("{} is not perfect".format(a))
except:
break
# include
# include
using namespace std;
int main(){
int n;
cin >>n;
while (n--){
int x;
cin>>x;
int s = 0;
for (int i=1;i*i<=x;i++)
if (x%i==0) {
if(i<x) s+=i;
if(i!=x/i && x/i<x) s+=x/i;
}
if(s==x) printf("%d is perfect\n",x);
else printf("%d is not perfect\n",x);
}
return 0;
}
import math
while True:
try:
n=int(input())
for _ in range(n):
a = int(input())
is_bool = True
for i in range(2,int(math.sqrt(a))+1):
if a%i==0:
is_bool=False
break
if is_bool:print("{} is prime".format(a))
else:print("{} is not prime".format(a))
except:
break
# include
# include
//这道题也是一样的,只需要枚举根号x此(x是需要判断的数)
using namespace std;
int main(){
int n;
cin >> n;
while (n--){
int p;
cin>>p;
bool is_prime = true;
for (int i=2;i*i<=p;i++){
if(p%i==0){
is_prime=false;
break;
}
}
if (is_prime) printf("%d is prime\n",p);
else printf("%d is not prime\n", p);
}
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)