Print all unique combination of factors of a given number

后端 未结 9 722
挽巷
挽巷 2021-02-08 05:46

What is the most efficient algorithm to print all unique combinations of factors of a positive integer. For example if the given number is 24 then the output should be

9条回答
  •  长情又很酷
    2021-02-08 06:44

    This code find all the factors of a number, sort them (locally and globally):

    public class PrimeFactors {
    
       final SortedSet< List< Integer >> _solutions = new TreeSet<>(
          new Comparator>(){
             @Override
             public int compare( List left, List right ) {
                int count = Math.min( left.size(), right.size());
                for( int i = 0; i < count; ++i ) {
                   if( left.get(i) < right.get(i)) {
                      return -1;
                   }
                   if( left.get(i) > right.get(i)) {
                      return +1;
                   }
                 }
                return left.size() - right.size();
             }});
    
       public SortedSet< List< Integer >> getPrimes( int num ) {
          _solutions.clear();
          getPrimes( num, new LinkedList< Integer >());
          return _solutions;
       }
    
       private void getPrimes( int num, List< Integer > solution ) {
          for( int i = num - 1; i > 1; --i ) {
             if(( num % i ) == 0 ) {
                int temp = num / i;
                List< Integer > s = new LinkedList<>();
                s.addAll( solution );
                s.add( temp );
                s.add( i );
                Collections.sort( s );
                if( _solutions.add( s )) { // if not already found
                   s = new LinkedList<>();
                   s.addAll( solution );
                   s.add( temp );
                   getPrimes( i, s );
                 }
             }
          }
       }
       public static void main( String[] args ) {
          SortedSet< List< Integer >> solutions =
             new PrimeFactors().getPrimes( 24 );
          System.out.println( "Primes of 24 are:" );
          for( List< Integer > l : solutions ) {
             System.out.println( l );
          }
       }
    }
    

    Outputs:

    Primes of 24 are:
    [2, 2, 2, 3]
    [2, 2, 6]
    [2, 3, 4]
    [2, 12]
    [3, 8]
    [4, 6]
    

提交回复
热议问题