a perfect number is defined as an integer which is the sum of its proper positive divisors, that is, the sum of the positive divisors not including the number. For example, the first perfect number is 6, because 1, 2 and 3 are its proper positive divisors and 1 + 2 + 3 = 6. Definition is from wikipedia.org
A:
import java.util.Vector;
public class PerfectNumber {
- private static Vector
v ;
private static void getAllFactors(int n){
- v = new Vector
();
if(n <= 2) return;
v.add(1);
int sqrt = (int)Math.pow(n, 0.5)+1;
for(int i=2; i < sqrt; i++){
- if((n%i) == 0){
- v.add(i);
v.add(n/i);
- v.add(i);
- if((n%i) == 0){
private static boolean isPerfectNumber(int num){
- getAllFactors(num);
int sum = 0;
for(int i=0; i < v.size(); i++){
- sum += v.get(i);
// System.out.println(num + " sum: " + sum);
if(sum == num) return true;
return false;
public static void printPerfectNumber(int range){
- for(int i=1; i < range; i++){
- if(isPerfectNumber(i)){
- System.out.print(i + ", ");
- if(isPerfectNumber(i)){
public static void main(String[] args) {
- System.out.println("Perfect numbers between 0 and 1000: ");
PerfectNumber.printPerfectNumber(1000);
- v = new Vector
Result:
Perfect numbers between 0 and 1000:
6, 28, 496,
No comments:
Post a Comment