147k views
0 votes
Can you write this java program?

❑ A perfect number is a positive integer that is equal to the sum of all its proper divisors (positive divisors of the number excluding the number itself). ▪ For example, the first (smallest) perfect number is 6 as 6 = 3 + 2 + 1.

❑ Write a method that ▪ has the header public static int sumProperDivisors(int num), ▪ computes the sum of all proper divisors of a given number (num) as the input argument ▪ and returns the computed sum.

User Yotka
by
8.1k points

1 Answer

5 votes

Here's a Java program that includes a method to compute the sum of all proper divisors of a given number:

```java

public class PerfectNumber {

public static void main(String[] args) {

int num = 6;

int sum = sumProperDivisors(num);

System.out.println("Sum of proper divisors of " + num + " = " + sum);

}

public static int sumProperDivisors(int num) {

int sum = 0;

for (int i = 1; i <= num / 2; i++) {

if (num % i == 0) {

sum += i;

}

}

return sum;

}

}

```

In this program, the `sumProperDivisors` method takes an integer `num` as an input argument and computes the sum of all proper divisors of `num`. It initializes the `sum` variable to 0 and then iterates from 1 to `num / 2` (since proper divisors are smaller than the number itself). If `i` is a divisor of `num`, it adds `i` to the `sum`. Finally, it returns the computed `sum`.

In the `main` method, we provide a sample number `6` as an example. You can modify the `num` variable to test with different numbers. The program will output the sum of proper divisors of the given number.

User JWo
by
8.6k points