Python factorization

Asked 2 years ago, Updated 2 years ago, 16 views

import math
N = int(input())
p=[]

if N == 1 :
    print("error")

while N !=1:
    if len(p)==0:
        start=2
    else:
        start=p[-1]
    for i in range(start,N+1):
        if N % i==0:
            #print(i)
            p.append(i)
            N=N//i
            break
        else:
            continue

I know how to factor things down

 [Example of input]
135

[Example of output]
3 ^ 3 X 5 ^ 1

I don't know how to print it out like this.

Help me

python

2022-09-20 16:33

1 Answers

Modify p to be collected by replacing it with a list of prime numbers.

You print it out using a join statement to match the output format that the problem wants.


import math
N = int(input())
p=[]

if N == 1 :
    print("error")

while N !=1:
    if len(p)==0:
        start=2
    else:
        start=p[-1]
    for i in range(start,N+1):
        count = 0
        while N % i==0:
            #print(i)
            count += 1
            N=N//i
        if count:
            p.append((i, count))


print('x'.join(' %d^%d '%(e[0], e[1]) for e in p))          


2022-09-20 16:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.