This is my first code in python and i completely can't get why the code in 5-th string must contain math.sqrt(i))+1 instead of just math.sqrt(i), because otherwise squares of prime numbers are added to the result.
How to solve this is the easiest and most natural way? Thanks you all in advance
import math
n=int(input("Print n: "))
prime_list=list(range(2,n))
for i in range(2,n):
for j in range (2, math.ceil(math.sqrt(i))+1):
if i % j == 0:
try:
prime_list.remove(i)
except:
j+=1
continue
print(prime_list)
You need j to run all the way through the sqrt of i. Remember that a Python range does not include the terminal value.
For instance, range(2, 7) does not include 7. To find that 49 is not a prime, you need range(2, 7+1), so that j will take on the value 7.
It's because it's Python.
In Python, the syntax range(x, y) generates a sequence of
x, x+1, x+2, ..., y-2, y-1
So if you want a value to be included in the range, the second parameter must be greater than the value (not equal), and that's why you should use math.floor(...) + 1 and cannot omit the +1 part. Otherwise when i is the squate of a prime, j will not iterate over that prime, thus causing the error you're facing.
Related
My homework is simple, declare a function named printPrimeNumbersTo with a single argument named to
I created the skeleton of the code itself, however, I needed some help from the net.
GeeksforGeeks was the site where I "borrowed" a line of code, which I don't completely understand. (Site: https://www.geeksforgeeks.org/python-program-to-print-all-prime-numbers-in-an-interval/)
My code looks like this (I have comments on nearly every line, describing what I think that the line of code does):
def printPrimeNumbersTo(to):
x = 0
prime_list = [] # This was a string, however, I changed it to a list so I won't have to convert the numbers to a string every time I wanted to append it to the list
for i in range(x, to + 1): # Create a for loop, using the function range an starting the loop at number 0. Add 1 to 'to', because range excludes the end integer
if i == 0 or i == 1:
continue
else:
for j in range(2, i // 2 + 1): # <--
if i % j == 0: # If 'j' is divided by any number in the list and remainder is 0, then the number is not a prime number, which means I can break the loop
break
else:
prime_list.append(i) # Append the prime number to the list
return str(prime_list)[1:-1] # Returns '[2,3,5,7..]', I use the square brackets the get rid of the brackets themselves
print(printPrimeNumbersTo(7)) # >>> 2, 3, 5, 7
The one line I don't understand is marked with an arrow, it's the 8th line of the code.
Why am I dividing the number by 2? And then making it an integer? When I do the calculations, it works, but... where is the logic? Anybody help?
The biggest number which could possibly be an even factor of a number is the half of that number. The integer division operator // produces this number as an integer.
Because of how range works, the ending index needs to be the desired number plus one.
There are two points to note:
the code needs to be indented correctly, in Python indentation matters as it forms the code blocks.
aside from this and specifically adressing the question: the range function that you refer to requires integers otherwise it would throw an typeerror like this: 'float' object cannot be interpreted as an integer .
# this will throw an error
for i in range(1, 10.5):
print(i)
# this will work
for i in range(1, 10):
print(i)
So the reason why the line of code you queried was written like that was to ensure that the upper bound of the range was an integer.
You should also note that the // has a meaning, for example try this:
x = 5//2
print(x)
y = 5/2
print(y)
x is the integer part only (x=2)
y is the full number (y=2.5)
In terms of implementaiton, there are a number of methods that would be better (suggested here):
Print series of prime numbers in python
Dividing the number by 2 is done to reduce the number of iterations. For example, the number 12 you can divide it without a remainder by 1,2,3,4,6. Notice that there is no number bigger than (6) which is 12 / 2. And this goes on with all of the numbers.
16 ---> 1,2,8 no number bigger than its half (8)
I can't understand the second for loop:
for k in range(2, n//2 + 1):
print(n%k, end=" ")
How did this formula produce such result?
range() has multiple parameters, first is start, second is stop, third is step (which is not present in this example, so the default value is used: 1).
So your range will generate numbers from 2 to n//2 + 1.
To learn more about range, and for loops:
https://www.w3schools.com/python/ref_func_range.asp
https://www.w3schools.com/python/python_for_loops.asp
The second for loop prints the reminders of dividing n by all of the numbers from 2 to n/2.
check the documentation of range
Assuming that n is a positive integer
this is my code:
def sum_odd_n(n):
x =1
for x in range(n):
if x%2==1:
continue
return x + 2
but when I run it on Python it gives me the answer 2. Could you help me by telling me what's wrong and what I should do to solve this?
Since you want to find the sum of first 'n' odd numbers, I suggest you to use range function with step=2. I'll elaborate:
def sum_n(n):
addition=0
for x in range(1,2*n,2):
addition+=x
return addition
s=sum_n(5)
print(s)
This gives output as: 25
Here, in range function, 1st attribute provides starting point, 2nd attribute provides the end point, and 3rd attribute gives the Difference between each number in the sequence.
I hope this helps.
There are a few problems with your code.
The first is that you have a return statement inside the for loop.
Secondly, you just visit the first n integers and check which of them are odd. You won't visit all the first n odd integers.
A list comprehension solution solution is as follows.
def sum_odd_n(n):
# sum up the first n odd numbers
return sum([2*i + 1 for i in range(n)])
Check this program it will work:
a=int(input("how many first odd number sum you want"))
x=1
i=0
def OddSum():
global i
global x
while i<=a:
x+=2
i+=1
print(x)
OddSum()
The question: Assume the availability of a function is_prime. Assume a variable n has been associated with positive integer. Write the statements needed to find out how many prime numbers (starting with 2 and going in increasing order with successively higher primes [2,3,5,7,11,13,...]) can be added before exceeding n. Associate this number with the variable k.
The code:
def is_prime():
i = 2
k = 0
Again = True
while Again = True:
if total > n:
Again = False
for x in range(2,n):
if x % i == 0:
total = total
k = k
i += 1
else:
total += x
k += 1
return k
Your code is not correct for an issue involving prime number tracking and consecutive addition. Nor anything else. The obvious issue is that it doesn't run, so it can't be correct. One syntax bug is this:
while Again = True:
which should be:
while Again == True:
Another is that total is never initialized before it's value is used:
total += x
Once we fix those problems, your code still doesn't appear to work. But let's back up a bit. The stated problem says,
Assume the availability of a function is_prime.
But you didn't do that -- you wrote your solution with the name is_prime(). We should expect that there is a function named is_prime(n) and it tests if n is prime or not, returning True or False. You are either given this, need to find one, write one, or simply assume it exists but never actually test your code. But once you have this function, and it works, you shouldn't change it!
Here's my example is_prime(n) function:
def is_prime(n):
""" Assume the availability of a function is_prime. """
if n < 2:
return False
if n % 2 == 0:
return n == 2
for m in range(3, int(n ** 0.5) + 1, 2):
if n % m == 0:
return False
return True
Now write your solution calling this function, but not changing this function. Here's one possible algorithm:
Write a function called primes_in_sum(n)
Set the variable prime to 2 and the variable k (our counter) to
0.
Subtract prime from n.
While n >= 0, increment k, and compute the next value of prime
by keep adding one to prime until is_prime(prime) returns true.
Then again subtract prime from n. Back to the top of this loop.
When the while condition fails, return k.
Test your code works by outputting some values:
for n in range(2, 100):
# Assume a variable n has been associated with a positive integer
print(n, primes_in_sum(n))
Check in your head that the results are reasonable.
I am trying to write a python function to return the number of primes less than a given value and the values of all the primes. I need to use the Sieve of Eratosthenes algorithm. I believe I'm missing something in the function - For example, when I want to find the primes under 100. All I got is 2, 3, 5, 7. I am aware that if I don't use "square root", I can get all the primes I need; but I am told that I need to include square root there. Can someone please take a look at my code and let me know what I am missing? Thanks for your time.
def p(n):
is_p=[False]*2 + [True]*(n-1)
for i in range(2, int(n**0.5)):
if is_p[i]:
yield i
for j in range(i*i, n, i):
is_p[j] = False
"I am told I need to use square root". Why do you think that is? Usually the sieve of E. is used to remove all "non prime" numbers from a list; you can do this by finding a prime number, then checking off all multiples of that prime in your list. The next number "not checked off" is your next prime - you report it (with yield), then continue checking off again. You only need to check for factors less than the square root - factors greater than the square root have a corresponding factor less than the square root, so they have alread been found.
Unfortunately, when it comes to printing out the primes, you can't "stop in the middle". For example, 101 is prime; but if you only loop until 11, you will never discover that it's there. So there need to be two steps:
1) loop over all "possible multiples" - here you can go "only up to the square root"
2) check the list for all numbers that haven't been checked off - here you have to "go all the way"
This makes the following code:
def p(n):
is_p=[False]*2 + [True]*(n-1)
for i in range(2, int(n**0.5)):
if is_p[i]:
for j in range(i*i, n, i):
is_p[j] = False
for i in range(2, n):
if is_p[i]:
yield i
print list(p(102))
The result is a list of primes up to and including 101.
Your logic is correct, except for the for loop. It terminates after reaching sqrt(n)-1. For p(100), it will run only from 2 to 9. Hence you get prime numbers only till 9.
Your use of the square root is terminating your results early. If you want to yield all the primes up to 100, your loop has to go to 100.
The square root isn't necessary in your code because it's implied in your second for loop. If i*i < n then i < sqrt(n).