Wednesday 2 August 2017

Java Code to tests the whether a given pair of numbers are amicable numbers

Problem:

Amicable numbers are pairs of numbers each of whose divisors add to the other number. Design and implement an algorithm that tests the whether a given pair of numbers are amicable numbers.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class AmicableNumbers {

int n1;
int n2;
List<Integer> firstNumberDivisors = new ArrayList<Integer>();
List<Integer> secondNumberDivisors = new ArrayList<Integer>();


public static void main(String[] args) {
AmicableNumbers amicableNumbers = new AmicableNumbers();
amicableNumbers.getTheNumbers();
amicableNumbers.findTheDivisors();
amicableNumbers.printTheDivisors();
amicableNumbers.printTheResult();
}

public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the first number in the pair");
n1 = scanner.nextInt();
System.out.println("enter the second number in the pair");
n2 = scanner.nextInt();
scanner.close();
}

public void findTheDivisors(){
for (int i = 1; i < n1; i++) {
if(n1%i == 0){
firstNumberDivisors.add(i);
}
}

for(int i = 1; i < n2; i++){
if(n2%i == 0){
secondNumberDivisors.add(i);
}
}
}

public void printTheDivisors(){
System.out.println("first number divisors are " + firstNumberDivisors);
System.out.println("second number divisors are " + secondNumberDivisors);
}
public boolean areAmicableNumbers(){
boolean result = false;
int firstNumberDivisorSum = 0;
int secondNumberDivisorsSum = 0;
for(Integer i: firstNumberDivisors){
firstNumberDivisorSum = firstNumberDivisorSum + i;
}
for(Integer i: secondNumberDivisors){
secondNumberDivisorsSum = secondNumberDivisorsSum + i;
}
if(firstNumberDivisorSum == n2 && secondNumberDivisorsSum == n1){
result = true;
}
return result;
}

public void printTheResult(){
System.out.println("Are the given numbers are amicable numbers ?? " + areAmicableNumbers());
}

}


Output:

enter the first number in the pair
220
enter the second number in the pair
284
first number divisors are [1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110]
second number divisors are [1, 2, 4, 71, 142]
Are the given numbers are amicable numbers ?? true

enter the first number in the pair
1184
enter the second number in the pair
1210
first number divisors are [1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592]
second number divisors are [1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605]
Are the given numbers are amicable numbers ?? true

enter the first number in the pair
221
enter the second number in the pair
280
first number divisors are [1, 13, 17]
second number divisors are [1, 2, 4, 5, 7, 8, 10, 14, 20, 28, 35, 40, 56, 70, 140]
Are the given numbers are amicable numbers ?? false

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...