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.
Related
so pretty straight forward, I had to write a code to check if a number if Prime or not. Code tested on Jupyter Notebook and works PERFECTLY. But whenever I put it in CodeWars, it passes the initial tests but later on when I submit the attempt, it times out, saying that the code may be "inefficient". Does anyone have an insight as to why this might be happening? Here is the code:
def is_prime(num):
mylist = []
if num != 1 and num > 0:
for number in range(1,num+1):
if num % number == 0:
mylist.append(number)
else:
pass
if len(mylist)>2:
return False
else:
return True
else:
return False
For large numbers, your time to compute will take too long.
I suggest looking more into the properties of prime numbers and reevaluating your code.
Ex: Properties of Prime Numbers!
can you try this and see how it works in CodeWars.
for num in range(1,7):
if all(num%i!=0 for i in range(2,num)):
print('Prime' , num)
I'm new to Python and testing myself with some questions. One that came up was to test whether a user inputted number was prime or not. Easy enough, but one person came up with a single line of code as a solution.
import math
num = int(input("Enter a number greater than 2 "))
if sum([True if num%factor == 0 else False for factor in ([2] + list(range(3,int(math.sqrt(num)),2)))]):
print("Number is composite")
else:
print("Number is prime")
I understand part of it: the if statement is True if (number/iterations) gives a remainder of 0, else False, where the only iterations that need to be checked are 2 -> sqrt(number) skipping all even numbers.
However, I can't work out how to sum operator at the start of the if statement works. I assume it operates on the True(1)/False(0) statements, but how does this interaction play out and how does it affect the if/else statements?
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)
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).
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