this code is working fine. say for 1980 it gives the result 2 ^ 2 *3 ^ 2 *5 ^ 1 *7 ^ 0 *11 ^ 1 *(an extra asterisk remains at the end. i can remove it. and that has nothing to with my problem.
the code is:
prime=[2,3,5]
f=7
def next_prime(f):
j=0
while j==0:
for x in prime:
if f%x==0:
f+=2
break
else:
j=1
return f;
def factorization(n):
list=[2,3,5]
power=[]
x=0
while x<len(list):
j=0
while n%list[x]==0:
j+=1
n=n/list[x]
power.append(j)
x+=1
if n!=1:
while n!=1:
g=next_prime(f)
j=0
while n%g==0:
j+=1
n=n/g
else:
power.append(j)
prime.append(g)
x=0
while x<len(power):
print(prime[x],"^",power[x],"*",end="")
x+=1
factorization(1980)
then if i want to remove the term 7 ^ 0 from the result therefore all the primes which have the power zero, i made change in line 31 (if j!=0: instead of else:). and then the code’s not working. it’s working for numbers like 13860 where no prime has the power zero not in numbers like 1980. i can’t find the problem!
the changed code is:
prime=[2,3,5]
f=7
def next_prime(f):
j=0
while j==0:
for x in prime:
if f%x==0:
f+=2
break
else:
j=1
return f;
def factorization(n):
list=[2,3,5]
power=[]
x=0
while x<len(list):
j=0
while n%list[x]==0:
j+=1
n=n/list[x]
power.append(j)
x+=1
if n!=1:
while n!=1:
g=next_prime(f)
j=0
while n%g==0:
j+=1
n=n/g
if j!=0:
power.append(j)
prime.append(g)
x=0
while x<len(power):
print(prime[x],"^",power[x],"*",end="")
x+=1
factorization(1980)
I haven’t analyzed your logic, but you’re using
elseclause wrongly.while .. elsemakes sense only if you call abreakinside yourwhile. In your first code sample, theelsebranch is always executed.As example, even the following code will run
elsebranch: