求正整数2和n之间的所有完全数【c/c++/java/python】
时间: 2023-12-09 20:01:31 浏览: 120
在c语言中,可以使用如下代码实现:
#include <stdio.h>
int isPerfectNumber(int num)
{
int sum = 1;
for (int i = 2; i*i <= num; i++)
{
if (num % i == 0)
{
sum += i;
if(i*i != num)
sum += num / i;
}
}
if (sum == num && num != 1)
return 1;
return 0;
}
int main()
{
int n;
printf("请输入一个正整数n:");
scanf("%d", &n);
printf("2和%d之间的完全数有:\n", n);
for (int i = 2; i <= n; i++)
{
if (isPerfectNumber(i))
printf("%d ", i);
}
return 0;
}
在java语言中,可以使用如下代码实现:
public class PerfectNumber {
public static boolean isPerfectNumber(int num) {
int sum = 1;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
sum += i;
if (i * i != num) {
sum += num / i;
}
}
}
return sum == num && num != 1;
}
public static void main(String[] args) {
int n = 100;
System.out.printf("2和%d之间的完全数有:\n", n);
for (int i = 2; i <= n; i++) {
if (isPerfectNumber(i)) {
System.out.printf("%d ", i);
}
}
}
}
在python语言中,可以使用如下代码实现:
def isPerfectNumber(num):
sum = 1
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
sum += i
if i * i != num:
sum += num // i
return sum == num and num != 1
def main():
n = 100
print(f"2和{n}之间的完全数有:")
for i in range(2, n + 1):
if isPerfectNumber(i):
print(i, end=' ')
if __name__ == "__main__":
main()
阅读全文