My Coding >
Programming language >
Python >
Exercise >
Python: How to calculate prime numbers
Python: How to calculate prime numbersPython: How to make generator of prime numbers How to calculate prime numbers in Python by function and generatorPrime numbers it is a numbers which you can divide to 1 and to itself only. For example, 1, 2, 3, 5, 7 – are prime numbers. 4 not a prime number, because 4%2==0 There are few mathematical formulas, how to calculate prime numbers, but we will make simple generator without these mathematical equations. We will use the fact, that for every number (N) we need to check remainder of the division for every numbers from 2 till sqrt(N)+1 and if we will not find any – then it is Prime number We will make this function as a generator for list and simple function. The difference will be only in the way of calling this function. Python generator of prime numbersThis is a generator, which will return next prime number after each call. We will make a call with lambda function via itertools.takewhile() and send all data to list
This will give for example: We can keep all calculated prime numbers in the list, and then use them for further prime tests to make it work faster like function below. Python function for prime numbersThis function is called once and it calculate full list of prime numbers between 2 and max input integer.
This will produce:
|
Last 10 artitles
9 popular artitles
|
|
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |