Java find all ends up within 1000
- 2020-06-12 09:02:49
- OfStack
Perfect Numbers (Perfect Number), also known as perfect or complete Numbers, are special natural Numbers of 1. The sum of all its true factors (that is, divisors other than itself) (that is, the factor function) is exactly equal to itself. If a number happens to be equal to the sum of its factors, it is said to be a "perfect number".
Requirement: Determine and output all perfect Numbers up to 1000.
If a number is exactly equal to the sum of its factors, it is called a finished number. For example, 6=1+2+3. Program to find all completion Numbers up to 1000.
public class Wanshu {
public static void main(String[] args)
{
int s;
for(int i=1;i<=1000;i++)
{
s=0;
for(int j=1;j<i;j++)
if(i % j==0)
s=s+j;
if(s==i)
System.out.print(i+" ");
}
System.out.println();
}
}
Method 2
public class PerfectNumber {
public static void main(String[] args) {
System.out.println("1000 All finishes within are: ");
for (int i = 2; i < 1000; i++) {// traverse 1000 All integers within
int sum = 0;// Definitions and variables
for (int j = 1; j < i; j++) {
if (i % j == 0) {// Meet is i The factor , Will accumulate
sum += j;
}
}
if (sum == i) {// The sum of the satisfy factors is equal to i Just print the end number
System.out.print(i + " ");
}
}
}
}