Maximum factors formed by two numbers in Python

PythonServer Side ProgrammingProgramming

We are given with an array of integer type elements and the task is to find the maximum factors formed by multiplying two numbers i.e. firstly we will multiply the numbers present in an array like calculating cross product secondly, we will calculate the factors of those numbers and check for the maximum factors amongst all.

Input

int arr[] = {3, 2, 10}

Output

Maximum factors formed by two numbers are: 8

Explanation

  • Calculate the inner cross product i.e. 3 * 2 = 6, 3 * 10 = 30, 2 * 10 = 20

  • Now calculate the factors for 6 -> 1, 2, 3, 6 ; 30 -> 1, 2, 3, 5, 6, 10, 15, 30 ; 20 -> 1, 2, 4, 5, 10, 20.

  • Check for the number with the maximum number of factors i.e. 6 have total 4 factors, 20 have total 6 factors and 30 have 8 factors. So maximum factors formed by two numbers are 8.

Input

int arr[] = {1, 4, 6}

Output

Maximum factors formed by two numbers are: 8

Explanation

  • Calculate the inner cross product i.e. 1 * 4 = 4, 1 * 6 = 6, 4 * 6 = 24

  • Now calculate the factors for 4 -> 1, 2, 4 ; 6 -> 1, 2, 3, 6 ; 24 -> 1, 2, 3, 4, 6, 8, 12, 24.

  • Check for the number with the maximum number of factors i.e. 4 have total 3 factors, 6 have total 4 factors and 24 have 8 factors. So maximum factors formed by two numbers are 8.

Approach used in the below program is as follows

  • Input the integer elements in an array
  • Take temporary variable multiple and big to store the maximum value
  • Start loop i from 0 till length of an array
  • Inside the loop, start another loop j from 0 till length of an array
  • Check whether a[i] not equals to a[j] if yes then set variable multiple with a[i] * a[j] and check if big < countFactor(multiple) then set big to count Factor(multiple)
    • In countFactor(multiple) function
      • Take temporary variable as int c = 0
      • Start loop for from j to 1 till multiple value
        • Check if multiple % j = 0
          • Then increment c by 1
      • Return c
  • Print the value of big

Example

public class BiggestFactor{
   public static void main(String[] args){
      int a[]={3,2,10};
      int multiple=1;
      int big=1;
      for(int i=0;i<a.length-1;i++){
         for (int j = 0; j < a.length; j++){
            if(a[i]!=a[j]){
               multiple=a[i]*a[j];
               if(big<countFactor(multiple))
                  big=countFactor(multiple);
            }
         }
      }
      System.out.println(“Maximum factors formed by two numbers are: ” +big);
   }
   private static int countFactor(int i){
      int c=0;
      for (int j = 1; j<=i; j++){
         if(i%j==0){
            c++;
         }
      }
      return c;
   }
}

Output

Maximum factors formed by two numbers are: 8
raja
Published on 03-Aug-2020 13:59:59
Advertisements