Java: Finding perfect numbers
A perfect number is a positive integer that is equal to the sum of its proper positive divisors excluding itself. It is also called aliquot sum. The first perfect number is 6, because 6=1 + 2 + 3. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14
Here is a java program for finding perfect numbers.
import java.util.ArrayList; public class IsPerfectNumber { public static boolean isPerfectNumber(int num) { boolean isPerfect = false; int sum=1; if(num<6)return false; for(int i=2; i<=num/2; i++) { if(num%i == 0) { sum += i; } } if(sum==num) return true; return isPerfect; } public static void main(String args[]) { int range = 10000; ArrayList<Integer> perfectNums = new ArrayList<Integer>(); for(int i=0; i<=range;i++) { if(IsPerfectNumber.isPerfectNumber(i)) perfectNums.add(i); } System.out.format("Perfect numbers within %s: %s\n",range,perfectNums.toString()); } }
Perfect numbers within 10000: [6, 28, 496, 8128]
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts