Posts

Showing posts with the label prime number

Python Program to Find Prime Factors of a Number

 In this post I am going to write a program in python that finds all the prime factors of a number. I am going to start by writing an empty function and a test. def get_prime_factors(number): prime_factors = [] return prime_factors if __name__ == "__main__": n = 8 expected = [2, 2, 2] result = get_prime_factors(n) assert expected == result, result Now, if you run the program above, it will give an AssertionError, as we are returning an empty list. Let's write some code to make our test pass. def get_prime_factors(number): prime_factors = [] while number % 2 == 0: prime_factors.append(2) number = number // 2 return prime_factors The program will work for multiple of 2's. Our next task is to find the other prime factors. For example, prime factors of 10 are 2 and 5. We shall add this test case first and then write code to pass this test....

Prime Number Generator in Python using Sieve Method

I have implemented a prime number generator in Python using Sieve of Eratosthenes . Here is my code: import math high = 10000 root = int(math.sqrt(high) + 1.0) ara = [x % 2 for x in xrange(0, high)] ara[1] = 0 ara[2] = 1 x = 3 while x I am looking for ideas to make my code faster. I tested my Python program using the code for solving a problem named Prime Generator in SPOJ . I could solve the problem correctly that took 3 seconds time and 3.8 MB memory. I am posting another code I found here . This one is similar implementation to mine but more Pythonic and much faster: nroot = int(math.sqrt(n)) sieve = [True] * (n+1) sieve[0] = False sieve[1] = False for i in xrange(2, nroot+1): if sieve[i]: m = n/i - i sieve[i*i: n+1:i] = [False] * (m+1) sieve = [i for i in xrange(n+1) if sieve[i]] I updated the above code and now it's 20% faster! :) nroot = int(math.sqrt(n)) sieve = [True] * (n+1) sieve[0] = False sieve[1] = False sieve[4: n+1:2] = [False] * (n / 2 -...

lambda magic to find prime numbers

Find prime number up to 100 with just 3 lines of code. The 4th line is for printing ;) nums = range(2, 100) for i in range(2, 10):     nums = filter(lambda x: x == i or x % i, nums) print nums Isn't it amazing? Check my new post about Prime number: http://love-python.blogspot.com/2010/11/prime-number-generator-in-python-using.html