Python: creating a range of numbers from a list - python

I am new to coding, and I am trying to write a somewhat generic prime number program. The difference with mine is that I want my program to be more efficient and only check numbers equal to, and including the square root of the number being checked, and I only want it to check previously found prime numbers. So far I have accomplished only the first criteria.
from numpy import sqrt, ceil
for a in range (3, 10000):
k=0
b=ceil(sqrt(a))
for i in range(2, int(b))
if (a%i==0):
k=k+1
if(k<=0):
print(a)
I think that I need to create a list with the number 2, run the program, and append any prime numbers that are printed to the list. However, I do not know how to:
1.) Make sure only numbers on said list are checked.
2.) Make sure only numbers through sqrt(a) are checked.
Any guidance is appreciated

You want to remember the primes that have been found, so store them in a list rather than just printing them. You mention appending primes as they are found; to do use primes.append(new_prime). Use break once you find a factor or once you pass the square root to skip to the next iteration.
primes = [2]
for tested_number in range(3, 10000, 2): #skip the evens
is_prime = True # if this is still true after testing, number is prime
for prime in primes:
if tested_number%prime == 0:
is_prime = False
break
elif prime>sqrt(tested_number): # no need to check these primes
break
if is_prime:
primes.append(tested_number)

Related

any() in python coding issue

I am trying to make a function that tells you if a number is prime or not using the any() method. This is what I have:
def prime(n):
if any(n % i == 0 for i in range(1, n + 1)) != True:
print("Prime")
else:
print("Not Prime")
prime(5)
However it is giving me:
Not Prime
every single time, even when I give a prime number.
Can someone please help me out?
Everything is divisible by 1, so that check will consider everything as non-prime. You need to set the lower bound to check to 2 instead.
As pointed out in the comments by #ForceBru, the upper bound is incorrect as well. You don't want to check if n is divisible by itself, since it always will be.
Change your range in the comprehension to just:
range(2, n))

My code works fine but every time the input is a prime number it keeps on printing "This is a prime number." over and over. How do I stop this?

My code is a PYTHON program that identifies if a number is prime or not. When I entered 45 however, it said that 45 was a prime, even though 45 isn't a prime number. Also, every time I run the program, it prints 'Sorry, the number you have entered is not prime.' or 'The number is indeed prime!' multiple times, instead of once. How do I make it print the output statements once and how can fix the program so that it says 45 IS NOT a prime number.
n = eval(input("Enter a number to find if that number is prime: "))
a = 2
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break
else:
print('The number you have entered is indeed prime!')
Because you are printing it every time. If you want to break after finding/not finding the prime number, indent one more level for the break.
Also, this does not calculate prime numbers. It calculates if its even number.
Follow the solution here
Your code has some issues. To start with, you're never updating a, so you only ever check if the number n is even.
Once you fix that, you have two indentation problems. The first is that the break line needs to be inside the body of the if statement. Indent it more so that it's inside the if block.
The second indentation issue is more subtle. If you leave the else where it is, it will print out that the number is prime every time you test a potential factor that doesn't divide the number. That's both unhelpful (since it prints a lot) and wrong (since it says the number is prime even if it will later find a factor and say it's not prime). You can fix this by unindenting the else line so that it is lined up with the while statement. Using an else after a loop is an obscure bit of Python syntax. The body of the else only runs if the condition of the loop fails. It gets skipped if the loop exits due to a break statement.
Here's all of those necessary fixes together:
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break # indent this line more!
a += 1 # increment a, so you don't keep checking 2 over and over
else: # unindent this line (and the next line too)
print('The number you have entered is indeed prime!')
There are some other things that could be improved in your code, though they aren't causing it to run incorrectly. I'd recommend using int instead of eval to parse your number, and I'd use the logical-and operator and instead of the bitwise-and operator & in the if statement (though actually you don't need either, since the a != n check is redundant, as the loop would have already ended if it was true).

Tough time understanding the below Python Script

I am new to coding and I am having a hard understanding the below code which prints all the prime numbers below 10.
N = 10
primes = []
for n in range(2,N+1):
for p in primes:
if n % p == 0: break
else:
primes.append(n)
print(primes)
My question is- what is the value of p during the first iteration? Isn't it 0? If so, n%p is always 0 right? Please help me understand.
A for..in loop over an empty list basically does nothing; it says "for each element in this list, do something", and since there is nothing in the list, it does nothing. So on the first iteration of the outer loop, the for p in primes does nothing at all, and the else clause is invoked.
On subsequent iterations there is something in primes, so the loop will get invoked and p will be populated with values.
The else clause of a for..in loop will be executed at the end of the loop, unless the loop is interrupted by break. That's exactly what is happening on your code: if the loop finds a divisible number, it breaks the loop and nothing happens, otherwise the number will get added to primes.
The algorithm in a nutshell is: for numbers from 2…10, if the number is not a multiple of an already discovered prime, it's a prime.

Sage (Python) Math Programming, Writing an Algorithm to check for Primality

I need to write a code in Sage for a homework problem that checks whether a random number generated between 10^7 and 10^8 is prime by dividing it by all the known primes less than or equal to 10^4. I have never programmed in Sage prior to this as a warning. This is what I have so far.
# This creates a function to create a random number between two numbers
def random_between(j,k):
a=int(random()*(k-j+1))+j
return a
# Testing that the function works, which it does, though I don't know how
# to assign a variable to it like x=random_between(10^7,10^8)
random_between(10^7,10^8)
# The list of primes less than 10^4 is given by
list_of_primes = prime_range(1,10^4)
# Want to write a function to check if prime
def check_if_prime(n):
for n in list_of_primes:
if n % random_between(10^7,10^8)==0:
print 'number is prime'
else
print 'number is not prime'
What I'm wanting to do is to use determine whether the numbers in list_of_primes divide the random number generated from random_between using the % command and then print that number x is a prime or that it's not.
I do know that the command Primes() will check whether a number is prime or not, but we are specifically supposed to do this "naive" check primality.
If someone could help me out with this I would really appreciate it.
You're check_if_prime function could use some work. I've re-written below.
def check_if_prime(): # there's no parameter for this method since we're checking against the global var list_of_primes
for n in list_of_primes:
if random_between(10^7,10^8) % n == 0: # if a random number / a prime number has no remainder, the random number is not prime
print 'number is not prime'
return # we're done, we know it's not prime
print 'number is prime' # we made it through all of our tests, the number might be prime

Python Printing Prime Numbers

TASK : Write a program that prints out all the primes below 10,000.
Hint: you will need to use % which gives the remainder of a division operation.
So x=11%5 would give 1 as 11/5=2 remainder 1
I FOUND THIS CODE , can someone add annotations next to all the lines explaining what is happening.I totally don't understand this code.
numbers=[]
for i in range(0,10001):
numbers.append(" ") #We just put spaces in each box for now
numbers[0]="X"
numbers[1]="X"
firstFree=2
while firstFree<10001:
multiple=firstFree*2
while multiple<10001: #Mark all multiples of firstFree as X
numbers[multiple]='X'
multiple=multiple+firstFree
firstFree=firstFree+1
while firstFree<10000 and numbers[firstFree]=='X':
firstFree=firstFree+1
for i in range(0,10001):
if(numbers[i]!='X'):
print(i)
As you have been told, you should not learn that way. Plus, in my humble opinion, this code you have found is extremely ugly and hard to read.
This is beter example.
#Main loop, this is self explanatory.
for dividend in range(2, 10000):
#This loops through all divisors available.
for divisor in range(2, dividend):
#Check against reminder of division.
if dividend % divisor == 0:
#Prints all composites of prime number that failed against check.
print('{} equals {} * {}'.format(dividend, divisor, dividend//divisor))
#Breakes second loop.
break
#Find answer for this thing yourself. It is interesting.
else:
#Enters here when have not found division factor.
print('{} is one of the prime numbers.'.format(dividend))
Read tons of tutorials, train and learn.

Categories