Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

 I have been given a java assignment to write a java program that finds amicable pairs under a value e.g. 1000 and it has to compare all numbers from 0 to that value we were given and find out which are amicable pairs and I the output must be 2 column matrix.

1 Answer

0 votes
by (13.1k points)

  You can something like this:

import java.util.*;

public class Main

{public static int sumoffactors(int n){

int sum=0;

for(int div=1;div<=n/2;div++){

    if(n%div==0){

        sum+=div;

    }

}

return sum;

}

    static int[][] Matrix(int limit){

        int[] arr=new int[limit];

        for(int i=2;i<limit;i++){

            arr[i]=sumoffactors(i);

        }

        Map<Integer,Integer> map=new HashMap<Integer,Integer>();

        for(int i=2;i<limit;i++){

            int j=arr[i];

            if(j<i && i==arr[j])

            map.put(i,j);

        }

        int[][] matrix=new int[map.size()][2];

        int index=0;

        for(int k:map.keySet()){

            matrix[index][0]=k;

            matrix[index][1]=map.get(k);

            index++;

        }

        return matrix;

    }

public static void main(String[] args) {

  int[][] matrix=Matrix(1000);

  for(int i=0;i<matrix.length;i++){

      System.out.println(matrix[i][0]+" "+matrix[i][1]);

  }

}

}

Want to learn java? Check out the java tutorial from Intellipaat. 

Related questions

Browse Categories

...