I am a new person to programming and still wrapping my head around the logic. The code I am laying out for you works: it produces the first N prime numbers. i.e. if user enters 10, the code will produce all primes up to and including 10. This was an assignment question, by the way. This is how my professor laid it out.
Also, if I am not displaying my code correctly, please give me some helpful hints about how to do that. I don't know what a fence is, but I indented each line 4 spaces, if that helps.
I stepped through this code in debug mode, and noticed that the value of j never went beyond 2 or 3. Why not?
n = int(input("Please enter the number up to which you want to find prime
numbers: "))
count = 0
if n > 1:
for i in range(2, n + 1):
isPrime = True # set flag to True
for j in range(2, i // 2 + 1):
if i % j == 0:
isPrime = False
break
if isPrime:
print(i, "is a prime number.")
count += 1
else:
print("Prime numbers must be greater than 1.")
print(count, "prime numbers have been found.")
There were no error messages that I could detect.
Related
the program is not running the way I want it to be.
number = int(input('Enter a number'))
if number < 2:
print('Number cannot be less than 2')
for digits in range(2,number+1):
for a in range(digits):
if number % a ==0:
print(number)
In the second loop, your running the range from 0 to digits which makes the first value of 'a'=0 throw us an error of zero-division.
number = int(input('Enter a number'))
if number < 2:
print('Number cannot be less than 2')
for digits in range(2,number+1):
flag = True
for a in range(2,digits):
if digits%a ==0:
flag = False
break
if(flag):
print(digits)
Here we need to use a boolean variable to know if it has satisfied the condition even once. If it does then it's not a prime number in that case we should not print the value.
This is a basic approach to solving this problem ( Time complexity - O(n^2))
we can use 2 more methods such as
n/2 +1
sqrt(n)+1
in the second loop to reduce the complexity.
refer this link for Most Optimized Method
You have your logic screwed up...
Remember, a number is prime if it's not divisible by any number from 2 to (n-1). So, going through a loop from 2 to n-1, if the modulo is 0, it's not a prime.
So, your first three lines are fine, assuming the spacing is corrected:
number = int(input('Enter a number'))
if number < 2:
print('Number cannot be less than 2')
You want a loop going from 2 to number--you get that with range(2, number+1). I'll call this loop i, because THAT'S THE LAW. (Just kidding, but i as a loop variable is common.)
Now we check each i with another loop going from 2 to i-1, which I'll call j. Again, if (i % j) is 0 at any point during this loop, i is not prime. Now, you could use a break statement, but just to make the code cleaner, we'll add another variable:
for i in range(2,number+1):
prime=True
j = 2
while j<i and prime:
if i%j == 0:
prime=False
else:
j += 1
if prime:
print i
Note that the while loop doesn't do anything when i=2, but that's fine since 2 is prime and gets printed. The last if ensures that for i>2, i is only printed if it went through the entire while loop without triggering if i%j == 0, which means none of the numbers are even divisors of i, which means i is prime.
Of course this isn't optimized, but it should work.
I'm trying to make a program that will stop when it gets 5 prime numbers from a range.
I've completed most of the program except the part where it is supposed to stop after it gets 5 numbers.
I've added a condition for it to stop, once the counter reaches 5 but it does not stop and continues to list all the numbers in the range.
Here is code I have:
condition = 0
while condition < 5:
for numbers in range(2,20):
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
The condition+=1 never goes through and it lists all the prime numbers from 1 to 20 even though I just want the first 5.
I've tried spacing options with the "condition +=1" but it still does not work
Any help would be appreciated
While is out of for loop, so cannot work obviously. A simple solution is to check required condition later:
for numbers in range(2,20):
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
if condition >=5:
break
I think the real problem you are having is that you have written bad code. A much better approach to this problem is to isolate as many pieces as possible.
for example:
def is_prime(x):
"return true if x is prime, otherwise false"
# implement me!
return True
def get_first_n_primes_less_than_y(n, y):
number = 2
condition = 0
while condition != n and number < y:
if is_prime(number):
print(number)
condition += 1
number += 1
get_first_n_primes(5, 20)
The above code, with some tweaking can perform the same task. However, code like this is much simpler to debug and reason about because we have isolated chunks of code (is_prime, has nothing to do with the while loop)
num_results = 5
counter = 0
range_start = 2
range_end = 20
# iterate range
for number in range (range_start, range_end):
# iterate divisors
for divisor in range (2, number):
# check division
if (number % divisor) == 0:
break
else:
print ("%s is a prime number" % number)
counter += 1
break
# check if number of results has been reached
if counter == num_results:
break
# check if number of results has been reached
if counter == num_results:
break
The problem is that you need to run the entire content of the while block before you test the condition again.
Here is a way around
condition = 0
numbers=2
while condition < 5 and numbers < 20:
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
numbers+=1
Recently I was given a challenge to my coding skills by my teacher since he saw that I was already knowledgeable in what he was teaching. The question is as follows.
Create a program that prompts the user for 2 numbers. The program will then display all the prime numbers in between the two given numbers, including the given numbers. Note: You cannot assume the first input is bigger than the second input.
So I took this question and built a fairly simple algorithm and ran it and it worked. I opened it today to find out for some reason my output is occasionally wrong, for example when you input 8 and 29 I get 27. I am looking for HINTS as to what is wrong with my logic because I cannot for the life of me figure out what Im doing wrong. I dont want straight up fixes because I would like to learn as much from this and doing it as much as possible by myself.
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
numList = []
#Removing Even Numbers
for num in range(numbers[0],numbers[1] + 1):
if num % 2 != 0:
numList.append(num)
#Checking For Prime Numbers
for currNum in numList:
#Set Start number to divide
i = 2
while i < currNum:
#Checks if the currNum can be divisble by i and is a whole number
if currNum % i != 0:
i = i + 1
else :
numList.remove(currNum)
break
print(numList)
From what I have learned from testing this out it seems like 27 is never checked during my for loop or while loop even though it is in the numList array.
Never remove items form a list you are iterating over.
Instead create a new list:
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
primes = []
for num in range(numbers[0], numbers[1] + 1):
#Set Start number to divide
i = 2
while i < num:
#Checks if the currNum can be divisble by i and is a whole number
if num % i == 0:
break
i += 1
else:
primes.append(num)
print(primes)
With this code, I only get to test if the number the user entered is prime or not.
How do I add another loop to my original code in order to find all the prime numbers less than or equal to the number the user has entered?
num = int(input("Enter a number: "))
if num > 1:
prime = True
for n in range(2, num):
if (num % n) == 0:
print ("Number", num, "is not prime")
break
else:
print("Number", num, "is prime")
You can'not print both in one loop, you can do one thing add a loop above your current loop and display each number like this :
num = int(input("Enter a number: "))
if num > 1:
prime = True
for n in range(2, num):
if (num % n) == 0:
print ("Number", num, "is not prime")
break
else:
print("Number", num, "is prime")
#your current code ends here
for j in range(2, num + 1):
# prime numbers are greater than 1
for i in range(2, j):
if (j % i) == 0:
break
else:
print(j)
Your code only check the number entered is prime or not , but you questioned about to get prime numbers from 2 to n (n = number entered by user) for this you run below code with the help of flag bit it will little bit easy for you. i hope it will help you.
Try This i run this code It will Surely help you to find your answer it work in python 3.0 or above
num = int(input("Enter The Number"))
if num > 1:
num = num+1
list = []
for j in range (2,num,1):
flag = 0
for i in range (2,int(j/2)+1,1):
if(j%i)== 0:
flag = 1
break
if flag==0:
list.append(j)
print(list)
else:
print("Enter Number Greater Than 1")
Aside from small things (unused boolean variable) your prime test is also super inefficient.
Let's go through this step by step.
First: To test if a number is prime, you don't need to check all integers up to the number for divisors. Actually, going up to sqrt(num) turns out to be sufficient. We can write a one-liner function to find out if a number is prime like so:
from numpy import sqrt
def is_prime(n):
return n > 1 and all(n%i for i in range(2,int(sqrt(n))+1))
range(2,some_num) gives an iterator through all numbers from 2 up to some_num-1and the all() function checks if the statement n%i is true everywhere in that iterator and returns a boolean. If you can guarantee to never pass even numbers you can start the range from 3 (of course with the loss of generality). Even if you don't want to use that function, it's cleaner to separate the functionality into a different function, because in a loop of numbers up to your input you will probably have to check each number for being prime separately anyways.
Second: From here, finding all primes smaller or equal than your input should be pretty easy.
num = int(input("Enter a number:"))
assert num>0, "Please provide a positive integer" # stops with an assertion error if num<=0
prime_lst = [2] if num > 1 else []
for x in range(3,num+1,2):
if is_prime(x):
prime_lst.append(x)
The list prime_lst will contain all your sought after prime numbers. I start the loop from 1 such that I can loop through only the odd numbers, even numbers are divisible by two. So this way none of the numbers will be divisible by two. Unfortunately this requires me to check if the number itself may be 2, which is a prime. By the twin-prime conjecture we can not simplify this range further without knowing about the input.
Finally: If you really want to find the primes in one loop, change your loop to something along the lines of:
prime_lst = [2] if num > 1 else []
for x in range(3,num+1,2): # outer loop
for i in range(3,int(sqrt(x))+1): # inner loop for check if x is prime
if x%i == 0:
break # breaks the inner loop, number is not prime
else:
prime_lst.append(x)
Edit: Just saw that the second answer here has a good explanation (and an even better way) of writing the one-liner for finding out if a number is prime.
I'm getting several incorrect answers in this code. For example, 9 is showing as prime. I'm guessing my problem is with using the breaks, but I can't seem to logically figure out what is wrong with this simple code someone asked me about.
for number in range(0, 1000):
for x in range(2, number):
if (number % x == 0):
break
else:
print x
break
In your script, regardless of if the number is divisble by 2 or not, it breaks the loop immediately.
I've reindented the code and this is probably closer to what you were trying to do.
In your original code, if the number is divisible by 2 (first number in the range(2,number), then you break the loop and if it is not divisible you also break the loop. So all odd numbers, like 9, looked like primes.
The else keyword after a for loop is run iff the loop exits normally. So the "is prime" part will only be printed if no divisor is found.
for number in range(0,1000):
for x in range(2,number):
if(number % x == 0):
print number,"divisible by",x
break
else:
print number, "is prime"
You can see this is anction here: http://codepad.org/XdS413LR
Also, this is a naive algorithm (not a critique of the code, exploring simple algorithms is a useful study), but you can make a little more efficient. Technically you only need to check as far as the sqare root of number, as any number larger than the square root must have a complement that is less than the square root, which should have already been encountered. So the logic in the code can be changed to:
from math import sqrt
for number in range(0,1000):
for x in range(2,int(sqrt(number/2))):
# Rest of code as above.
That said there are many ways that you can optimise the checking or discovery of prime numbers that are worth investigating if you get the chance.
I think you want something like this:
for number in xrange(100):
for i in range(2,number):
if number % i == 0:
break
else:
print number
this iterates through every number form 1-100 and checks if any number is divisible by any # besides one but you need the else: statement out side of the inner for loop so if it goes throught the inner for loop without finding a divisor its prime
Here are some alternatives. First, this checks for primes:
def check_for_prime(n):
if n == 1: return False
elif n == 2: return True
elif n%2 == 0: return False
# Elementary prime test borrowed from oeis.org/A000040.
odds = 3
while odds < n**.5+1:
if n%odds == 0: return False
odds += 2
return True
This is slightly faster, but you should have experience using yield:
def primes_plus():
yield 2
yield 3
i = 5
while True:
yield i
if i % 6 == 1:
i += 2
i += 2
Here are some alternatives.
n is the number till the range you want to find
n=100
for i in range(0,n):
num = filter(lambda y :i % y == 0,(y for y in range(2,(i/2))))
if num or i == 4:
print "%s not a prime number" %(i)
else:
print "%s is a prime number" %(i)