The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.(I am not getting what is wrong in this code) - python-3.x

sum = 2
x=3
y=5000
for i in range (x,y):
for j in range (2,i):
if i%j==0:
break
elif i%j!=0 and j==i-1:
sum += i
if i==y-1 and y<2000000:
x=y
y+=5000
else:
continue
print(sum)
**I am not getting what is wrong in this code. By running this I came to know that the Last If and Else statement are not running **

Given your code, there are a couple of things wrong. First, sum is a python function name and should never be used as a variable name. It will get you into trouble in more ways than I care to think about. Second, the last else statement is not needed, because whether the if clause above it is or is not executed executed, the for loop will be executed again. Third, I don't understand the purpose of y and the magical value 5000, unless you are trying to provide an end value for your loop. The problem with this approach is you seem to try and extend it's range in increments of 5000. The problem is that once the initial for loop is executed, it creates a local iterable from x to 5000, and subsequent changes to y do not affect the for loops range.
I would approach the problem differently, by creating a list of primes and then use the python sum method to add all the values. Here is the code:
def sum_primes(max_prime):
""" Return Sum of primes Less than max_prime"""
primes = [2]
indx_num = 3
while primes[-1] <= max_prime:
update = True
for prime in primes:
if indx_num == prime or indx_num % prime == 0:
update = False
break
if update:
primes.append(indx_num)
indx_num += 2
#return summ of all values except the last
return sum(primes[:-1])
Executing sum_primes(2000000)
yields 1709600813

Related

Estimating value of 1/pi using Ramajunam equation, returning wrong value when comparing with (1/math.pi)

Edited for Updated code
#racraman. Love you man. You not only helped me improve my code but also to understand the Equation. Thanks for your time.
import math
# performing ramanujan's infinite series to
#generate a numerical approximation of 1/pi:
""" 1/pi = (2*sqrt(2))/9801) * (4*k)!*(1103+26390k)/(((k!)**4)*396**(4k)))"""
def factorial_1(k):
if k==0:
return 1
else:
result = k* factorial_1(k-1)
return result
def estimate_pi():
k=0
total=0
n=(2*math.sqrt(2)/9801)
limit=int(input("Enter the ending limit = ")) #k=0 until limit=infinity!!!!
while True:
m=factorial_1(4*k)*(1103+26390*k)
o=((factorial_1(k))**4)*(396**(4*k))
result=n*(m/o)
total+=result #assigning result to a new variable to keep track of changes
if k>limit:
break
k+=1 #updating value of k, to improve result & total for each loop.
return 1/total # Return's pi=3.14 only if k=0
print(estimate_pi())
The statement :
k = result
is the problem - the variable k cannot be both a loop counter and the running total.
Instead of that statement, you will need to simply decrement k, and also add result to a new running total variable that you initialise to 0 outside the loop.
You would also only want to print the result and return only after the loop has finished.
EDIT TO ADD :
Please don't use Answers in that way; that's not what they're for, and would be confusing for other readers to try to follow. The question is for containing all (ongoing) steps of defining the problem (just mark the appended updates with "EDIT TO ADD" as I have done with this comment); the answers are for solutions to that problem, to be accepted if they proved useful.
Ramanujan's formula most certainly works for increasing values of k - but you have to iterate starting at 0.
For example, let's say the user enters 5 for k.
What your code is currently doing is incrementing k - so calculating k = 5, 6, 7, ..... terminating when the step's result is 0. You're missing out k=0, 1, 2, 3, 4 - the major terms !
What you want to do instead is sum the results for k = 0, 1, 2, 3, 4, 5 so how about :
Have the user enter a variable limit instead of k
Start k at 0, and increment at each iteration
Terminate the loop when the step's result < epsilon, or k > limit
Incidentally, the n=(2*math.sqrt(2)/9801) is a constant, so can go outside the loop therefore get calculated only once.
#racraman. I'm Posting the updated code as an answer do that I could keep track of the Error's I've made for future references. Thanks for the Help.
# performing ramanujan's infinite series to
#generate a numerical approximation of 1/pi:
""" 1/pi = (2*sqrt(2))/9801) * (4*k)!*(1103+26390k)/(((k!)**4)*396**(4k)))"""
def factorial_1(k):
if k==0:
return 1
else:
result = k* factorial_1(k-1)
return result
def estimate_pi():
k=int(input("enter the value of k = "))
total=0
while True:
n=(2*math.sqrt(2)/9801)
m=factorial_1(4*k)*(1103+26390*k)
o=((factorial_1(k))**4)*(396**(4*k))
result=n*(m/o)
total+=result #assigning result to a new variable to keep track of changes
epsilon=1e-15
if abs(result)<epsilon:
break
k+=1 #updating value of k, to improve result & total for each loop.
return 1/total # Return's pi=3.14 only if k=0
print(estimate_pi())

Why is this code giving inaccurate result?

I am trying to print sum of all prime numbers between 2 and a given number N that would be input by the user. so if the input number is 10 the output should be 17. my code below though it works but not providing accurate results. what seems to be the issue here?
N=int(input())
sum_prime=0`enter code here`
#Calculate primes between 2 to N
for value in range(2,N+1):
if value>1:
for i in range(2,value//2+1):
if value%i==0:
break
else:
sum_prime+=value
print(sum_prime)
I understood your error. You add numbers to sum_prime even though the loops to check if it really a prime aren't finished. You have to move the addition out of the loop, like this for instance:
N=int(input())
sum_prime=0
#Calculate primes between 2 to N
for value in range(2,N+1):
is_prime = True # note that I have added a new variable
for i in range(2,value//2+1):
if value%i==0:
is_prime = False
break
if is_prime:
sum_prime += value # the addition is now out of the inner loop
print(sum_prime)
If I input 10, it correctly outputs:
17

(Python 3) Spent an hour but couldn't find the error

I am a beginner at learning python 3 and I am just writing basic programs. I wrote this simple program which would take a number in and divide it by numbers starting from 1 to the square root of the number and find the remainders and add it to a list and print it.
import math
def prime_checker(num):
n=1
list_of_remainder=[]
while n == math.floor(num**0.5):
var=int(num % n)
list_of_remainder.append(var)
n += 1
return list_of_remainder
var=prime_checker(10)
print(var)
Please tell me what I did wrong. I would like to point out here that I did try to research a bit and find error but I couldn't and only then have I posted this question.
The problem that I faced was that it printed out an empty list.
to start with, your while loop is not executed even once. The condition for your while loop is
while n == math.floor(num**0.5):
The argument num you are passing to the function prime_checker is equal to 10. In this case your condition test is:
while 1 == math.floor(10**0.5)
which is
while 1 == 3 which is obviously not true and as a result the loop is not executed even once.
import math
def prime_checker(num):
list_of_remainder = []
number=num;
n=1
x=math.floor(number**0.5)
while n <= x:
v=int(number % n)
list_of_remainder.append(v)
n += 1
return list_of_remainder
var=prime_checker(10)
print(var)

Is there any trick or method to count recursion calls on paper(with larger numbers)?

Hi everyone it is my first question here! I would like to ask about some tricks how can we count recursive calls in a paper, without using computer? The language in example is Python 3.xx. In this example if I get larger number like 11 how can I count number of stars in this example "easily"?
def func(numb):
print('*', end='')
if numb <= 1:
return False
for i in range(numb):
if func(i) and numb%i == 0:
return False
return True
func(11)
I found too uneffective, to write everything as the program running, especially if it is on a test, too time consuming.
Thank you for helping!
There are several methods of counting recursive calls; this one basically is iteration, I guess, you do
T(n) + T(n - 1) + T(n - 2) ... // in which T(n) is the complexity of the recursive call
Substitution will lead to the same result and master theorem is useless here, so that's the best you can do, and since every one of your calls is linear this ends up being (worst case scenario, of course):
n + (n - 1) + (n - 2) ... + 2 // since you end at 1
But you can actually reduce your recursive calls if you do this:
if numb%i == 0 and func(i): // you won't reach func(i) if num % i != 0
Please check these function.
def recursion(numb):
if(numb<1):
return False
print('*'),
numb-=1
recursion(numb)
recursion(11)
print('')
def recursion1(numb):
if(numb<1):
return False
for i in range(numb):
print('*'),
print('')
numb-=1
recursion1(numb)
recursion1(11)

Please can someone explain me these commands about python?

>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
I don't understand what the above command wants to do.
I know about looping but can you explain what this command is actually doing?
Python's for and while loops have a feature that may look confusing to people who are more familiar with those loops in other programming languages: You can put an else clause after the loop body.
The else block will be run only if the loop terminated in the normal way (a for loop reaching the end of the iterable or a while loop's condition being false). It will not be run if the loop was terminated by a break statement.
In the code you're looking at, the inner loop tests to see if the number n is prime by testing if it can be evenly divided by any x value. If an x does divide it exactly, the factors x and n // x are printed and a break statement ends the loop.
If no such factor is found in the range, the loop ends. As I mentioned above, this the situation where the else block is run. It prints that n is prime.

Resources