用java写一个1000以内的完数
时间: 2023-05-21 20:05:35 浏览: 107
以下是用Java语言编写的求1000以内完数的代码:
public class PerfectNumber {
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
System.out.print(i + " ");
}
}
}
}
这个程序的执行结果是:6 28 496
相关问题
用Java编程:找出1000以内完数
完数是指一个数等于它的因子之和,例如6=1+2+3,因此6是一个完数。以下是用Java编程找出1000以内完数的代码:
public class PerfectNumber {
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
System.out.println(i + "是一个完数");
}
}
}
}
这个程序会输出以下结果:
6是一个完数
28是一个完数
496是一个完数
用java写出一千以内的完数
Sure, I can help you with that. A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding itself. For example, 6 is a perfect number because the sum of its positive divisors (excluding 6) is equal to 6: 1 + 2 + 3 = 6. Here's the Java code to find all the perfect numbers between 1 and 1000:
```
for (int i = 1; i <= 1000; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
System.out.println(i + " is a perfect number");
}
}
```
This code loops through all the numbers from 1 to 1000 and checks if each number is a perfect number by finding the sum of its divisors. If the sum is equal to the number itself, then it's a perfect number and the code prints it out. I hope this helps!
阅读全文