|
After 34 seconds: import itertools
def factors(n):
result = set()
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
result.add(i)
result.add(n // i)
return sorted(result)
def main():
n = 108
factors_list = factors(n)
triplets = []
for a_idx in range(len(factors_list) - 2):
a = factors_list[a_idx]
for b_idx in range(a_idx + 1, len(factors_list) - 1):
b = factors_list[b_idx]
for c_idx in range(b_idx + 1, len(factors_list)):
c = factors_list[c_idx]
if a * b * c == n and a < b < c:
triplets.append((a, b, c))
print("All ways in which three distinct positive integers have a product of 108:")
for triplet in triplets:
print(triplet)
if __name__ == "__main__":
main()
Run: -▶ python a.py
All ways in which three distinct positive integers have a product of 108:
(1, 2, 54)
(1, 3, 36)
(1, 4, 27)
(1, 6, 18)
(1, 9, 12)
(2, 3, 18)
(2, 6, 9)
(3, 4, 9)
Too smart for its own good, maybe? Still, apparently correct on the first try.There's an import for `itertools` which isn't used, just as noted in the article for 4o. Can someone who knows what it's about say how optimal this version is, compared to other answers? |
Algorithmically it is optimal, many corner cases thought of to make as few loops as possible.
But it is suboptimal in the sense that it uses for loops so it is not possible for an underlying engine to execute in parallel, or to optimize the looping in native (e.g. C) code.
In short - the for loops are 'how'. Without loops it is much more 'what' which leaves it up to the computer to optimize