I have a prime factorization program:
import sys
import math
def prime_factorize(n):
factors = []
number = math.fabs(n)
while number > 1:
factor = get_next_prime_factor(number)
factors.append(factor)
number /= factor
if n < -1:
factors[0] = -factors[0]
return tuple(factors)
def get_next_prime_factor(n):
if n % 2 == 0:
return 2
for x in range(3, int(math.ceil(math.sqrt(n)) 1), 2):
if n % x == 0:
return x
return int(n)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: %s <integer>" % sys.argv[0])
exit()
try:
number = int(sys.argv[1])
except ValueError:
print("'%s' nie jest liczba calkowita!" % sys.argv[1])
else:
print ("%d =" %number, *prime_factorize(number), sep='*')
The program returns for 123456:
123456 =*2*2*2*2*2*2*3*643
And I wanted to get output in format:
123456 = 2^6*3*643
The best solution is to convert tuple to string? How to get this output format?
CodePudding user response:
I believe this is what you are after:
...
else:
tup = prime_factorize(number)
print("{} = {}".format(number, "*".join("{}^{}".format(x, tup.count(x)) if tup.count(x) > 1 else str(x) for x in sorted(set(tup)))))
Output:
123456 = 2^6*3*643