Python prime listing error - python

n = int(input("input n"))
prime = [2]
base = 3
order = 0
while base < n + 1:
if order < len(prime):
if base % prime[order] == 0:
order = len(prime)
else:
order += 1
else:
prime.append(base)
order = 0
base += 1
print (prime)
I am trying to create a list of prime numbers from 1 to given number 'n'.
(ignoring the case for numbers less than 3)
What I intend to do is:
bring first number from 3 to n (let's call this base)
compare base to first number in prime list (in this case, 2)
if the base is not divisible, compare this to next number in prime list.
repeat step 3 until all numbers in the prime list are compared or at least one number divisible to base in the prime list appears.
if base compared to all numbers in the prime list and is not divisible by any of them, append base to prime list.
increase the value of base by 1 and repeat step 2 to 5 upto base = n.
Whatever the value i put for n, i only get single value of 2 in the prime list printed. Please help to find out which part is wrong.

The reason your code is failing is because you are not actually checking through all of the stored prime numbers correctly - you need a second loop for this. Fortunately, Python makes this easy for you in two different ways: A list of values can be easily looped through, and else is supported by for. The modified code should look something like this:
n = int(input("input n"))
prime = [2]
base = 3
while base < n + 1:
for p in prime:
if base % p == 0:
# base is NOT a prime, break out
break
else:
# loop ran to completion
prime.append(base)
base += 1
print (prime)
So instead of some other if statement that doesn't quite do what you think it does, we instead use a for loop check all values in the prime list (assign that to p) and do the division as you might expect. If the modulus is 0, the loop breaks uncleanly and the else block will not run, and if none of the primes result in a modulus of 0 the else block will be triggered, adding that newly discovered prime number to the list and so on.
Example:
$ python3 foo.py
input n19
[2, 3, 5, 7, 11, 13, 17, 19]
If you wish to keep the existing logic (i.e. no for loops), you can do another while loop inside and remember to set order to 0 before it.

Related

Python, trying to sum prime numbers, why is '7' not getting appended?

I am trying to make a simple function to sum the prime numbers of a given input. I am wondering why '7' isn't coming up in my appended list of prime numberS:
def sum_primes(n):
empty = []
for i in range(2,n):
if n % i == 0:
empty.append(i)
print(empty)
sum_primes(10)
Your method for determining if numbers are prime is a bit off. Your function seems to determine if the input num n is prime but not sum all prime numbers to it.
You could make an isprime function and then loop over that for all numbers less than n to find all primes.
Actually your program have logical error. First you have to understand the prime number logic.
Step 1: We must iterate through each number up to the specified number in order to get the sum of prime numbers up to N.
Step 2: Next, we determine whether the given integer is a prime or not. If it is a prime number, we can add it and keep it in a temporary variable.
Step 3: Now that the outer loop has finished, we can print the temporary variable to obtain the total of primes.
sum = 0
for number in range(2, Last_number + 1):
i = 2
for i in range(2, number):
if (int(number % i) == 0):
i = number
break;
if i is not number:
sum = sum + number
print(sum)
def sum_primes(y):
sum = 0
# for each number in the range to the given number
for i in range(2, y):
# check each number in the sub range
for j in range(2, int(i/2)+1):
# and if its divisble by any number between
# 2 and i/2
if i % j == 0:
# then it is not a prime number
break
else:
# print current prime
print(i)
# add prime to grand total
sum += i
return sum
print(sum_primes(10))
I think you have some problems with the way you are checking if your number is prime or not. A much simpler way would be to use a library that does this for you. It takes less time, is usually a better implementation than you or I could come up with, and it takes fewer lines, therefore, looking cleaner.
I would recommend primePy. Its whole point is to work with prime numbers.
I don't have my computer with me atm so I can't make any sample code for you and test it. But something like this should work.
from primePy import primes
prime_list = primes.upto(n)
print(prime_list)
I believe that function returns a list of all prime numbers up to n. And if you wanted to get the sum of all of those numbers, you can go about whatever method you want to do that.
Afterward, slap it into a def and you should be good to go.
If it doesn't work let me know, and I will try to test and fix it when I am in front of a computer next.

Print prime numbers within an interval [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
This code is running for the 1-10 interval but for interval 20-30 it is writing 21 and 27 and I am unable to understand what's wrong in the code. I don't want to know other code; I want to know what's wrong in my code.
start = int(input("Enter the first number of the interval")) #starting of interval
end = int(input("Enter the last number of the interval")). #end of interval
for i in range(start, end+1):
for x in range (2,end):
if (i == 0 or i==1):
break
elif (i % x != 0):
print(i)
break
else:
break
for x in range (2,end):
if (i == 0 or i==1):
break
elif (i % x != 0):
print(i)
break
else:
break
This part of code should
print a number if it's prime, otherwise break
but it doesn't.
Do you notice something strange in your code? I do, and it's the fact that in every case the inner for loop breaks after the first iteration, rethink this aspect of your code, and it will work fine.
First, I am not sure whether you want the period after the inputting for the end. Also, your code checks if i is not divisible by x, then print. So for example, your code checks if 21 is divisible by 2. It is not, so your code prints it out and breaks.
Introduction
Your code is effectively testing if a number is odd and if it is, it prints it out.
If start is 1 and end is any number greater than 1, your code is printing every odd number greater than 2 in the interval [1, end].
It is printing all odd numbers, but not all odd numbers are prime!
Dissecting your code
Let's consider the [1, 20] interval. Your code outputs every odd number greater than 2 in the interval [1, 20].
3, 5, 7, 9, 11, 13, 15, 17, 19.
2 is prime and is missing from this list. We can fix that by writing the following within the outer loop but above the inner loop:
if i == 2:
print(i)
Now the output is `
2, 3, 5, 7, 9, 11, 13, 15, 17, 19.
This is better but 9, 15 are not prime numbers.
The if statement with condition (i == 0 or i == 1) inside of your inner loop is not causing any problems. Let's simplify the inner loop by moving this just outside of the inner loop (just above) so that your code becomes
for i in range(start, end+1):
if (i == 0 or i == 1):
# 0 and 1 are not prime
continue
if (i == 2):
# 2 is prime
print(i)
for x in range (2,end):
if (i % x != 0):
print(i)
break
else:
break
All that remains as the potential culprit for your problems is the inner loop so let's focus on that.
Whenever i is even, in the first iteration of the inner loop, we
have x = 2. We know that if i is even that i % 2 is 0 and so i % x != 0 is False and so we move onto the else, in which case we
break out of the inner for loop. This is all fine because no even
integer greater than 2 is prime!
Whenever i is odd, in the first iteration of the inner loop, we
have x = 2. We know that if i is odd that i % 2 is NOT 0 and so
i % x != 0 is True and then we print i and then break out of
the for loop.
We never once have x = 3 or x = 4 and so on!
The above describes precisely what you code is doing, which is ignoring even integers and simply printing out every odd integer.
Solution that outputs what you want
It would help me if I knew what definition of a prime number you have and/or what algorithm you are trying to implement. But since I don't have this information, I can only suggest a solution.
In order to solve your problem, you need to clearly have in mind what a prime number is. There are many equivalent definitions of a prime number (see the Wikipedia prime number page for examples of definitions). I chose a definition that suggests a natural algorithm for finding prime numbers. Whatever definition of prime number you were given, it is possible to prove mathematically that it is equivalent to this (for some this is the first definition of a prime number that they see!):
An integer i is prime if and only if i > 1 AND for all k in {2, 3,
..., i - 1}, i % k != 0.
In words this says that an integer i is prime iff i is strictly greater than 1 and for all integers k from 2 up until i - 1, k does not divide i evenly.
Here it is
start = int(input("Enter Start: "))
end = int(input("Enter End: "))
print(f"\nPrime numbers between [{start}, {end}]:")
for i in range(start, end + 1):
if (i == 0 or i == 1):
# i is not prime
continue
if (i == 2):
# i is prime
print(i)
continue
for x in range(2, i):
if (i % x) == 0:
break
if (i % x) != 0:
print(i)
Example session:
Enter Start: 20
Enter End: 30
Prime numbers between [20, 30]:
23
29
The (i == 0 or i == 1) check should be placed outside the inner for loop. Otherwise, for all i greater than or equal to 2, for every iteration in the inner loop, you will be checking to see if it is less than 2 or not. You are doing this check too much.
We know that when i == 2 that i is prime.
For i > 2, we appeal to the definition of a prime number above.
The inner loop and the last statement applies the second part of the prime definition.

How to fix error in python code, which will not run over large numbers?

I have written a recursive Python program which I have attached below, which prints out the palindromic primes in an interval. I cannot use loops.
palindromic_primes.py:
import sys
sys.setrecursionlimit(30000)
# this function places all the numbers between the start and end points into
# a list and determines whether they are prime numbers by seeing if they have
# a remainder of 0 when divided, else numbers that dont have remainder of zero
# are stored.
def check_prime(num_list, number):
if num_list == []:
print(number)
else:
num = num_list[0]
if number % num == 0:
pass
else:
num_list.pop(0)
check_prime(num_list, number)
# this checks whether the numbers in the interval are palindromes by comparing
# the first 'letter' to the last 'letter' for each number and seeing whether
# they match.
def check_palindrome(nums):
nums1 = nums[::-1]
if nums1 == nums:
new_list = list(range(2, int(nums)))
check_prime(new_list, int(nums))
# this takes both functions and only stores the numbers that match in both
# functions.
def check_done(lists):
# takes numbers not stored (so the numbers that are palindromes and primes)
if lists != []:
check_palindrome(str(lists[0]))
lists.pop(0)
check_done(lists)
start_int = int(sys.argv[1])
ending_int = int(sys.argv[2])
palindromic_primes = print("The palindromic primes are:")
# the list will analyse all numbers from the start point till the end point
list1 = list(range(start_int, ending_int+1))
check_done(list1)
I have an error that I am not sure how to fix as the code works fine until I enter an input such as starting point 10000 and ending point 20000, as it gives me a segmentation fault.
when entered to wing IDE, this is what given back [evaluate palindromeprimes.py] Enter the starting point N: 10000 Enter the ending point M: 20000 The palindromic primes are:aborted (disconnected). when I enter it into my school marking system I get this: Your program produced: Enter the starting point N: Enter the ending point M: Segmentation fault Input supplied to your program: 10000 20000 Differences in the files are as follows: 1,29c1,3
Apparently, i need to make my code more efficient, but I'm not sure how to go about this. I saw told to think of the properties of prime numbers and factors, such as the fact that prime numbers are all odd. Factors occur in pairs, so if the number has no factors before some 'midpoint' then it wont have any after that 'midpoint' either
If your problem is one of computational efficiency then it's not necessarily a Python question
These facts should help to reduce the recursion depth:
There are many more palindromic numbers than primes - therefore check
your number is a prime BEFORE you check it's a palindrome
To check a number is not a prime you only need to check that the
modulus is zero when you divide by number up to (and including) the square root of the candidate
You only need to check that the number modulus is zero when you
divide by prime numbers (if it's divisible by 9, 15, 21 ..., it is divisible by 3)

Creating a tool for divisors

import requests
def repeat():
x = int(input("Common divisors of: "))
listrange = list(range(2,x))
emptylist = []
for number in listrange:
if x % number == 0:
emptylist.append(number)
print (emptylist)
elif x % number not in listrange:
print ("Prime number")
while True:
repeat()
Whenever I run this code it it prints prime number several times no matter what I type in.
What I want it to do instead is to give all common divisors for any integer except for 1 and the integer. If the integer is a prime number I want it to print prime number.
However as I previously mentioned this causes a problem for some reason resulting in that whenever the code is executed it prints prime number over and over again even though an elif statement is used.
Your current logic prints 'Prime number' every time it encounters an integer in the range which doesn't divide the number, irrespective of whether any other numbers divide it (i.e. it is not prime) or not (i.e. it is prime).
This logic corrects that:
def repeat():
x = int(input("Common divisors of: "))
listrange = list(range(2,x))
emptylist = []
for number in listrange:
if x % number == 0:
emptylist.append(number)
if not emptylist: #Checks if emptylist is empty i.e. is prime
print ("Prime number")
else:
print (emptylist)
e.g.
Common divisors of: 5
Prime number
Common divisors of: 28
[2, 4, 7, 14]
Your x % number not in listrange is going to be true a lot of the time, even for prime numbers. It is the wrong thing to test for prime numbers.
Say you start with 7, a prime number. The first number to be tested is 2:
>>> x = 7
>>> number = 2
>>> x % number
1
So the remainder is 1. 1 is not in the listrange() values (which go from 2 through to 6, inclusive). That's because for any given prime number larger than 2, division by 2 will always result in 1 as the remainder, and 1 is never in your list.
2 is not the only such value for which the remainder of the division is 1. For the prime number 7919, there are 7 such numbers:
>>> [i for i in range(2, 7919) if 7919 % i < 2]
[2, 37, 74, 107, 214, 3959, 7918]
so your code will print Prime number 7 times. And the test would be true for non-prime numbers too; 9 is not a prime number, but 9 % 2 is 1 too, so your code would claim 9 to be a prime number. For 1000, not a prime number, your code would print Prime number 32 times!
You can't state that a number is a prime number until you have tested all the values in listrange() and have determined that none of those numbers can divide the number without a remainder. So you need to test after you loop; you could test if emptylist is empty; that means there were no divisors, the very definition of a prime number:
for number in listrange:
if x % number == 0:
emptylist.append(number)
if not emptylist:
print ("Prime number")
As a side note: you don't need to turn a range object into a list of numbers, not only does testing if number in range(...): work, it's a lot faster than using the same test on a list.

Printing primes less than 100?

I am new to programming and trying to write a program that prints primes less than 100. When I run my program I get an output that has most of the prime numbers, but I also have even numbers and random odd numbers. Here is my code:
a=1
while a<100:
if a%2 == 0:
a+=1
else:
for i in range(2,int(a**.5)+1):
if a%i != 0:
print a
a+=1
else:
a+=1
The first part of my code is meant to eliminate all even numbers (doesn't seem to fully work). I also don't fully understand the part of my code (for i in).
What exactly does the "for i in" part of the code do? What is 'i'?
How can I modify my code that it does accurately find all of the primes from 1-100?
Thanks in advance.
See the comments on your post to find out why your code doesn't work. I'm just here to fix your code.
First of all, make use of functions. They make code so much more readable. In this case, a function to check if a number is a prime would be a good idea.
from math import sqrt
def is_prime(number):
return all(number%i for i in range(2, int(sqrt(number))+1))
There isn't much left to do now - all you need is to count how many primes you've found, and a number that keeps growing:
primes= 0
number= 1
while primes<100:
if is_prime(number):
print number
primes+= 1
number+= 1 # or += 2 for more speed.
Suddenly it's very easy to read and debug, is it not?
I'm going to try to guide you without giving you any code to help you learn, you should probably start from scratch I think and make sure you know how each part of your code works.
Some things about primes, 1 isn't prime and 2 is so you should start with a=3 and print 2 immediately if you want to eliminate even numbers.
By doing that, you will then be able to just increment a by 2 rather than 1 as you're doing now and just skip over even numbers.
As you loop a to be less than 100, you need to check if each value of a is prime by making another loop with another variable that loops downward through all numbers that could possibly divide a (less than or equal to a's square root). If that variable divides a, then exit the inner loop and increment a, but if it makes it all the way to 1, then a is prime and you should print it, then increment a.
There's several things wrong with what you're doing here:
You don't find the first 100 primes, you find the primes less than 100 with while a < 100
You print a every time a is evenly divisble by i, and then increment a. But you've gotten ahead of yourself! a is prime only if it is not divisble by any value i, but you fail to keep track of whether it's failed for any i.
You add +1 to the range up to the square root of the number - but that's not necessary. The square root of the number is the largest number that could possibly be the smaller of two factors. You don't need to add 1 because that number is _bigger than the sqare root - in other words, if a is evenly divisble by sqrt(a)+1 , then a / (sqrt(a)+1) will be smaller than sqrt(a)+1 and therfore would have already been found.
You never print the list of primes you found; you print a every time you find a number that is not a factor ( primes have no factors other than one and themselves, so you're not printing prime numbers at all!)
This might get you thinking in the right direction:
a=0
primes = []
while len(primes) < 100:
a = a + 1
prime=True
maxfactor = int(a ** .5)
for i in primes:
if i == 1:
continue
if i > maxfactor:
break
if a % i == 0:
print a, " is not prime because it is evenly divisble by ", i
prime=False
break
if prime:
print "Prime number: ", a
primes.append(a)
for p in primes:
print p

Categories

Resources