Sum of all prime numbers - python-3.x

I want the sum of all prime numbers till 2 million. My program logic is correct but it takes too much time with 2 million. How can I make it faster?
num_l=[]
y = int(input("enter till what number do you want the sum"))
for count in range(0,y):
num_l.append(count)
total = 0
for counter in range(0,y):
num = num_l[counter]
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
total = total + num
print(total)

just use a function to check that it is prime or not and if it is then add it to a counter (for total). The code below takes about 20 seconds to find what you want.
One more thing is that your algorithm for testing if a number is prime or not is having a long range of numbers to go through you don't need to test to the last number you just need to go through for a range of square root of the number.
import time
def is_prime(n):
if n == 1:
return False
elif n == 2:
return True
else:
for i in range(2, int(n**0.5)+1): # this range is just enough
if n % i == 0:
return False
return True
counter = 0
start = time.time()
for i in range(1, 2*10**6): # you can change this range for taking it as input
if is_prime(i):
counter += i
print(counter)
print(time.time() - start)

Related

How to find the sum of prime numbers upto a certain range in Python?

I'm absolutely new to Python and programming in general so it'd be helpful if someone can give very beginner friendly help. I'm trying to get the sum of prime numbers upto say 50.
I used the below code but it adds additional 2 on my sum. for example sum of prime number upto 50 should be 326 but I get 328 as my output
upto = int(input("Find sum of prime numbers upto : "))
sum = 0
for num in range(2, upto + 1):
for i in range(2, num):
if (int(num % i) == 0):
break;
#If the number is prime then add it.
else:
sum += num
print("\nSum of all prime numbers upto", upto, ":", sum)
Your Code is working fine and the answer of " sum of prime numbers from 1 to 50" is 328 not 326, if you still have doubt about it you can check your result with this code below :
Explanation: Given a range [l, r], the task is to find the sum of all the prime numbers within that range.
# from math lib import sqrt method
from math import sqrt
# Function to compute the prime number
def checkPrime(numberToCheck) :
if numberToCheck == 1 :
return False
for i in range(2, int(sqrt(numberToCheck)) + 1) :
if numberToCheck % i == 0 :
return False
return True
# Function to iterate the loop
# from l to r. If the current
# number is prime, sum the value
def primeSum(l, r) :
sum = 0
for i in range(r, (l - 1), -1) :
# Check for prime
isPrime = checkPrime(i)
if (isPrime) :
# Sum the prime number
sum += i
return sum
# Driver code
if __name__ == "__main__" :
l, r = 1, 50
# Call the function with l and r
print(primeSum(l, r))
I set your range in the code above just copy and paste the code in your editor and run the code , you will see the result.
There are two parts you need to handle. One is to check if the number is a prime number or not. Second is to iterate through the range of numbers. Refer to the code below,
from math import sqrt
sum = 0
#some explanation here we are iterating from 50 all the way to 1. So you can indicate your range here. -1 is the step value which tells the difference between each iteration.
for i in range(50, 0, -1):
# Check whether it is a prime number here
bPrime = True #initialize a boolean here to be indicated by the loop below
for a in range(2, int(sqrt(i)) + 1):
if i % a == 0:
bPrime = False #definitely not a prime,break the loop and set boolean to false
break
bPrime = True #not ==0 so it is a prime, set boolean to true
if (bPrime) :
# Add up if it is a prime number
sum += i
#view the results
print(sum)
It should get you 328
Hi Sumit firstly Welcome to Stackoverflow :)
Now as per your question the sum of prime numbers upto range 50 is 328 only, not 326.
But if you want the sum of first 50 odd prime numbers then you can make minor change in your code as below which will give you 326 [which is the sum of odd prime nos till range 50]
upto = int(input("Find sum of prime numbers upto : "))
sum = 0
for num in range(3, upto+1):
for i in range(2, num):
if (int(num % i) == 0):
break;
#If the number is prime then add it.
else:
sum += num
print("\nSum of all prime numbers upto", upto, ":", sum)

How can you print the prime numbers from 0 to 100 in python

I am writing a small program to find all prime number from a range from 0 to whatever number the user want. How should I fix my code?
I tried to swap the loop position and the algorithm but it didn't work
g=int(input("type"))
def check_prime(g):
if(g<2):
return False
for x in range(2, g+1):
v=int(math.sqrt(x))
if(x%v==0):
return False
return True
if check_prime(g):
print(x)
I expect when the user input g they will get all the prime numbers from 0 to g and also the program will tell them how many prime numbers found
It's pretty simple, this code below will return you both the count of primes and their values.
g=int(input("type"))
def check_prime(g):
count = 0
primes = []
for number in range(g+1): #considering 'g' is inclusive
primes.append(number)
count += 1
if(number < 2 or number%2 == 0):
primes = primes[:-1]
count -= 1
continue
for x in range(3, number, 2):
if (number % x) == 0:
primes = primes[:-1]
count -= 1
break
return count, primes
print (check_prime(g))

Time limit exceeded python

Im a newbie at python and i have a task. Given a number as input, i have to print the prime that belongs in the number/position on a list of primes starting from position 1 and not 0, until the input is 'END'. For example, if the input is 1, output should be the first prime which is 2, if the input is 5, output should be the 5th prime which is 11 and so. It works fine but after 3/4-digit numbers the output has a delay until i get the Error: Time limit exceeded. How can i make it run faster? Here's the code:
def primes_function(n):
primes = []
num = 2
while len(primes) <= n:
x = num // 2
while x > 1:
if num % x == 0:
break
x -= 1
else:
primes.append(num)
num += 1
return primes[n - 1]
#main
while True:
n = input()
if n == 'END':
break
elif n > '0':
n = int(n)
value = primes_function(n)
print(value)
Sorry if i made any mistakes in the description
enter image description here
I combined this answer (1) and this answer (2) to speed up the function. The two key ideas are: When testing primality of a candidate ...
... do not divide by every number (2, 3, 4, 5, 6, ...) but only by the preceding prime numbers (2, 3, 5, ...). Every non-prime number > 2 is has to have some prime factor.
... divide only by numbers that are ≤ sqrt(candidate).
import math
def nth_prime(n):
prime_list = [2]
candidate = 3
while len(prime_list) < n:
max_factor = math.sqrt(candidate)
is_prime = True
for p in prime_list:
if p > max_factor:
break
elif candidate % p == 0:
is_prime = False
break
if is_prime:
prime_list.append(candidate)
candidate += 2
return prime_list[-1]
Benchmark of different solutions:
n=9000 n=15000 n=25000 n=75000
your solution 1m38.455s - - -
linked answer (1) 0m 2.954s 8.291s 22.482s -
linked answer (2) 0m 0.352s 0.776s 1.685s 9.567s
this answer 0m 0.120s 0.228s 0.410s 1.857s
Brij's answer 0m 0.315s 0.340s 0.317s 0.318s
For every n the programs where started from scratch.
As we can see, Brij's Sieve Of Eratosthenes takes a fairly low constant amount of time. If you want to find big prime numbers below a fixed limit then that's the best solution (here n < 78499, as the 78499-th prime number is 1 000 003 which is bigger than the sieve list).
If you also want to find a lot of smaller or medium sized prime numbers or cannot accept a fixed limit then go with this solution.
def SieveOfEratosthenes():
n = 1000000
prime = [True for i in range(n+1)]
p = 2
count = 0
while (p * p <= n):
if (prime[p] == True):
count = count + 1
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
seive = []
for p in range(2, n):
if prime[p]:
seive.append(p)
return seive
def primes_function(n , seive):
return seive[n - 1]
#main
seive = SieveOfEratosthenes()
while True:
n = input()
if n == 'END':
break
elif n > '0':
n = int(n)
value = primes_function(n,seive)
print(value)
Full working : https://ide.geeksforgeeks.org/QTSGQfhFV3
I have precomputed the primes below 10^6 and made a list of primes and accessed the nth prime number by the index.

Euler 12 need optimization

I have solved euler problem 12, but it needs some optimization. I have read on the euler forums, but it has not helped me optimized it. However, I have managed to get the solution, I just need to speed it up. It currently takes 4 minutes to run. Here is my code:
import time
def nthtriangle(n):
return (n * (n + 1)) / 2
def numberofnfactors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
def FirstTriangleNumberWithoverxdivisors(divisors):
found = False
counter = 1
while not found:
print(int(nthtriangle(counter)), " ", numberofnfactors(nthtriangle(counter)))
if numberofnfactors(nthtriangle(counter)) > divisors:
print(" first triangle with over ",divisors, " divisors is ", int(nthtriangle(counter)))
found = True
break
counter += 1
start_time = time.time()
FirstTriangleNumberWithoverxdivisors(500)
print("My program took", time.time() - start_time, "to run")
Instead of calculating each triangle number individually, use a generator to get the triangle numbers
from timeit import timeit
def triangle_numbers():
count = 1
num = 0
while True:
num += count
count += 1
yield num
def count_divisors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
print(timeit('next(num for num in triangle_numbers() if count_divisors(num) >= 500)',
globals=globals(), number=1))
Gives me 3.8404819999996107 (seconds) on my machine. You could probably also improve the divisor counting.
What's really slowing you down is calling nthtriangle and numberoffactors more than once in your loop! Plus, those calls to print aren't free.

How to sum numbers from input?

I am working on the following problem.
Write a program that continually prompts for positive integers and stops when the sum of numbers entered exceeds 1000.
But my code stop early if a negative integer is entered.
The numbers will not sum.
My code:
x = int(input("Enter an integer:"))
total = 0
sum = 0
while (0 <= x):
if sum <= 1000:
x += 1
sum += (int(input("Enter an integer:")))
elif sum >= 1000:
break
x = 0
total = 0
sum = 0
while sum <= 1000:
x = int(input("Enter an integer:"))
if x<0:
print("Invalid negative value given")
break
sum += x
First:
if sum >= 1000:
...
elif sum < 1000:
...
is redundant, because if you chek for sum >= 1000, and the elif is reached, you aready know, that the condition was False and therefore sum < 1000 has to be true. So you could replace it with
if sum >= 1000:
...
else:
...
Second:
You want to use x to check, whether the input is negative. Until now, you were simpy increasing it by one each time. Instead, you should first assing the input to x, and then add this to sum. So do it like this:
x = int(input("Enter an integer:"))
if x<0:
break
sum += x
In case you want to stop as soon as you encounter the negative number.
x = 0
total = 0
sum = 0
while (sum <= 1000):
x = (int(input("Enter an integer:"))
if (x < 0):
break
else:
sum += x

Resources