PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] how to represent multiplicty of prime factor in factorization in python

 July 21, 2022     factorization, format, integer, python, python-requests     No comments   

Issue

I code this function factorization(n)... like below

def factorization(n):
    factor=[]
    for i in range(2,n+1):
        while n % i == 0:
            n = n/i
            factor.append(i)
        print(factor)

and if you write this factorization(180) = [2,2,3,3,5] but i want to print this format: 180 = 2^2 x 3^2 x 5

but i cant make it. i think 'list counting' is useful but i don't know how to use it correctly the number of each factor, and format it.


Solution

Using vanilla python & some formatting:

def factorization(n):
    factor = []
    for i in range(2, n + 1):
        while n % i == 0:
            n = n / i
            factor.append(i)
    print('*'.join(f'{n}' + (f'^{factor.count(n)}' if factor.count(n) > 1 else '') for n in set(factor)))


factorization(180)

Prints:

2^2*3^2*5


Answered By - rdas
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing