Find Prime factor of a number is one of most common question encounter in basic mathematics . But it has very high uses not only in mathematics problems but also in high level algorithmic programming problems. Mostly problems that uses properties of numbers .
If you wan't to become a programmer ,you will face many problems that uses properties of numbers , and we know a good programmer always try to find best way to solve problem otherwise there is always a straight way (Brute force way ) to solve almost any problem .
But we know it will ruin speed of programming result that's why we always try to find fastest and effective way to solve problems .
If you wan't to become a programmer ,you will face many problems that uses properties of numbers , and we know a good programmer always try to find best way to solve problem otherwise there is always a straight way (Brute force way ) to solve almost any problem .
But we know it will ruin speed of programming result that's why we always try to find fastest and effective way to solve problems .
Algorithm to Find prime factor of a number :
- Let number is n
- Set encounter to 2 (i.e i=2)
- Now divide n by i
then update value of n by n/i (n = n/i)
then go to step 3 again
Else :- continue
- Now check if i > squire root of n :-then stop iterating and exit
- Else : increment counter by 1 ( i = i+1) and goto step 3
Python Program to Find prime factor of a number :
- # Find prime factor of a number
- # http://beginer2cs.blogspot.com
- # Python 2.7
- import math
- def prime_fact(n):
- '''
- return a list ,contain prime factor of n
- '''
- flag=True # we Use this to continue or come out from while loop
- pf=[]
- i=2 # we start iteration from 2 (just as an counter)
- sq = math.sqrt(n) # this is end point of iteration ( Think why ??)
- while(flag): #start iteration
- if n%i == 0: #if i is factor of n
- pf.append(i) #then append it in list
- n=n/i #and update value of n by n/i
- elif i>sq : #test for end of iteration
- flag =False
- else:
- i = i+1 # increment counter by 1
- return pf
- if __name__=='__main__':
- n=int(raw_input('Enter ur number : '))
- print prime_fact(n)
Output :
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT