Problem:
A perfect number is one whose divisors add up to the number.
Design and implement an algorithm that prints all perfect numbers between 1 and 500.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
public class PerfectNumbers {
List<Integer> divisorsList = new ArrayList<Integer>();
List<Integer> perfectNumbersList = new ArrayList<Integer>();
public static void main(String[] args) {
PerfectNumbers perfectNumbers = new PerfectNumbers();
perfectNumbers.findThePerfectNumbers();
perfectNumbers.printTheResult();
}
public void findThePerfectNumbers(){
for(int i = 1; i <= 500; i++){
findTheDivisors(i);
if(isPerfectNumber(i)){
perfectNumbersList.add(i);
}
}
}
public void findTheDivisors(int number) {
divisorsList = new ArrayList<Integer>();
for (int i = 1; i < number; i++) {
if(number%i == 0){
divisorsList.add(i);
}
}
}
public boolean isPerfectNumber(int number){
boolean result = false;
int divisorsSum = 0;
for(Integer i: divisorsList){
divisorsSum = divisorsSum + i;
}
if(divisorsSum == number){
result = true;
}
return result;
}
public void printTheResult(){
System.out.println("the perfect numbers between 1 and 500 are: " + perfectNumbersList);
}
}
Output:
the perfect numbers between 1 and 500 are: [6, 28, 496]
A perfect number is one whose divisors add up to the number.
Design and implement an algorithm that prints all perfect numbers between 1 and 500.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
public class PerfectNumbers {
List<Integer> divisorsList = new ArrayList<Integer>();
List<Integer> perfectNumbersList = new ArrayList<Integer>();
public static void main(String[] args) {
PerfectNumbers perfectNumbers = new PerfectNumbers();
perfectNumbers.findThePerfectNumbers();
perfectNumbers.printTheResult();
}
public void findThePerfectNumbers(){
for(int i = 1; i <= 500; i++){
findTheDivisors(i);
if(isPerfectNumber(i)){
perfectNumbersList.add(i);
}
}
}
public void findTheDivisors(int number) {
divisorsList = new ArrayList<Integer>();
for (int i = 1; i < number; i++) {
if(number%i == 0){
divisorsList.add(i);
}
}
}
public boolean isPerfectNumber(int number){
boolean result = false;
int divisorsSum = 0;
for(Integer i: divisorsList){
divisorsSum = divisorsSum + i;
}
if(divisorsSum == number){
result = true;
}
return result;
}
public void printTheResult(){
System.out.println("the perfect numbers between 1 and 500 are: " + perfectNumbersList);
}
}
Output:
the perfect numbers between 1 and 500 are: [6, 28, 496]
No comments:
Post a Comment