Improve code to find prime numbers

2024/10/14 8:29:20

I wrote this python code about 3 days ago, and I am stuck here, I think it could be better, but I don't know how to improve it. Can you guys please help me?

# Function
def is_prime(n):if n == 2 or n == 3:return Truefor d in range(3, int(n**0.5), 2):if n % d == 0:return Falsereturn True
Answer

A good deterministic way to find relatively small prime numbers is to use a sieve.

The mathematical principle behind this technique is the following: to check if a number is prime, it is sufficient to check that it is not divisible by other primes.

import mathdef is_prime(n):# Prepare our Sieve, for readability we make index match the number by adding 0 and 1primes = [False] * 2 + [True] * (n - 1)# Remove non-primesfor x in range(2, int(math.sqrt(n) + 1)):if primes[x]:primes[2*x::x] = [False] * (n // x - 1)return primes[n]# Or use the following to return all primes:# return {x for x, is_prime in enumerate(primes) if is_prime}print(is_prime(13)) # True

For reusability your could adapt the above code to return the set of all prime numbers up to n.

https://en.xdnf.cn/q/117977.html

Related Q&A

How to read the line that contains a string then extract this line without this string

I have a file .txt that contains a specific line, like thisfile.txt. . T - Python and Matplotlib Essentials for Scientists and Engineers . A - Wood, M.A. . . .I would like to extract lines that contain…

Python: How to access and iterate over a list of div class element using (BeautifulSoup)

Im parsing data about car production with BeautifulSoup (see also my first question):from bs4 import BeautifulSoup import stringhtml = """ <h4>Production Capacity (year)</h4>…

What should I worry about Python template engines and web frameworks? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…

Value Search from Dictionary via User Input

I have written the following code for getting an output of the various districts located in the given city and their respective postal codes. I want my code to be able to receive input from the user (D…

Read and aggregate data from CSV file

I have a data file with the following format:name,cost1,cost1,cost1,cost2,cost3,cost3, X,2,4,6,5,6,8, Y,0,3,6,5,4,6, . . ....Now, what I would like to do is to convert this to a dictionary of dictionar…

nltk cant using ImportError: cannot import name compat

This is my codeimport nltk freq_dist = nltk.FreqDist(words) print freq_dist.keys()[:50] # 50 most frequent tokens print freq_dist.keys()[-50:] # 50 least frequent tokensAnd I am getting this error mess…

Fitting and Plotting Lognormal

Im having trouble doing something as relatively simple as:Draw N samples from a gaussian with some mean and variance Take logs to those N samples Fit a lognormal (using stats.lognorm.fit) Spit out a n…

Is there any way to install nose in Maya?

Im using Autodesk Maya 2008 on Linux at home, and Maya 2012 on Windows 7 at work. Most of my efforts so far have been focused on the former. I found this thread, and managed to get the setup there work…

Basic python socket server application doesnt result in expected output

Im trying to write a basic server / client application in python, where the clients sends the numbers 1-15 to the server, and the server prints it on the server side console. Code for client:import soc…

creating dictionaries to list order of ranking

I have a list of people and who controls who but I need to combine them all and form several sentences to compute which person control a list of people.The employee order comes from a txt file: