Print all unique combination of factors of a given number

后端 未结 9 721
挽巷
挽巷 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:43

    1) If i < num and i > num/2, then num % i == num - i. (Easy to prove.) So your for loop will pointlessly check all the integers greater than num/2 and the if statement will only succeed once, with temp == 2. I don't think that's what you wanted.

    2) In you fixed that, the recursion might need to produce a lot of answers. But you only print temp * once. So the output will look a bit wierd.

    3) isprime is unnecessary. num is always a legitimate factor, whether or not it is prime, provided you follow the point below.

    4) Finally, you need to figure out how to avoid printing out the same factorization multiple times. The easy solution is to only produce factorizations where the factors are monotonically non-increasing (as in your example). In order to do that, the recursion needs to produce factorizations with some maximum factor (which would be the previously discovered factor.) So the recursive function should have (at least) two arguments: the number to factor and the maximum allowed factor. (You also need to deal with the problem I noted as point 4.)

    The following Python code does (I believe) solve the problem, but it still does quite a few unnecessary divides. In a deviation from python style, it prints each factorization instead of acting as a generator, because that will be easier to translate into Java.

    # Uses the last value in accum as the maximum factor; a cleaner solution
    # would have been to pass max_factor as an argument.
    def factors(number, accum=[]):
      if number == 1:
        print '*'.join(map(str, accum))
      else:
        if accum:
          max_factor = min(accum[-1], number)
        else:
          max_factor = number
        for trial_factor in range(max_factor, 1, -1):
          remnant = number / trial_factor
          if remnant * trial_factor == number:
            factors(remnant, accum + [trial_factor,])
    

    It is possible to optimize the for statement. For example, once you compute remnant, you know that the next remnant must be at least one greater, so you can skip a bunch of trial_factor values when remnant is small.

提交回复
热议问题