Write a function (say, sum_primes) in python3 that takes in a number and returns the sum of all primes less than or equal to that number.
I tried like:
def sum_primes(num):
total = 0
for i in range(2, num+1):
if num%i == 0:
break
else:
total += i
return total
sum_primes(11)
but doesn't work.
you can try this way:
#Take the input from user
upto = int(input("Find sum of prime numbers up to : "))
sum = 0
for num in range(2, upto + 1):
i = 2
for i in range(2, num):
if (int(num % i) == 0):
i = num
break;
#If the number is prime then add it.
if i is not num:
sum += num
print("\nSum of all prime numbers upto", upto, ":", sum)
Related
I have to count the sum of all prime numbers that are less than 1000 and do not contain the digit 3.
My code:
def primes_sum(lower, upper):
total = 0
for num in range(lower, upper + 1):
if not num % 3 and num % 10:
continue
elif num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
total += num
return total
total_value = primes_sum(0, 1000)
print(total_value)
But still I don't have right result
def primes_sum(lower, upper):
"""Assume upper>=lower>2"""
primes = [2]
answer = 2
for num in range(lower, upper+1):
if any(num%p==0 for p in primes): continue # not a prime
primes.append(num)
if '3' in str(num): continue
answer += num
return answer
The issue in your code was that you were checking for num%3, which checks whether num is divisible by 3, not whether it contains a 3.
How can I display the first 25 integer prime numbers in the given interval? I can't find a way to limit it to 25 integer prime numbers.
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
for num in range (minimum, maximum + 1):
if num > 1:
for i in range (2, num):
if (num % i) == 0:
break
else:
print(num)
you have to use a counter to store how many prime numbers you've found.
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
counter = 0
for num in range (minimum, maximum + 1):
if counter == 25: break
if num > 3:
for i in range (2, int(num/2)): # for optimization
if (num % i) == 0:
break
else:
counter += 1
print(counter,num)
else:
counter += 1
print(counter,num)
here is the more optimized code with the hints in the comments:
import math
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
counter = 0
for num in range (minimum, maximum + 1):
if counter == 25: break
if num > 3:
if (num % 2) != 0:
for i in range (3, math.ceil(math.sqrt(num)), 2):
if (num % i) == 0:
break
else:
counter += 1
print(counter,num)
else:
counter += 1
print(counter,num)
If nothing else, you could use a variable to keep track of how many you've printed and break from the outer loop when that hits 25.
Here's an example, added to your code.
minimum = 1000000000
maximum = 9999999999
printed = 0
print ("The first 25 10-digit prime numbers are:")
for num in range (minimum, maximum + 1):
if num > 1:
for i in range (2, num):
if (num % i) == 0:
break
else:
print(num)
printed+= 1
if printed >= 25:
break
You can try this.
from sympy import isprime
i=1
count = 0
while count < 25:
if isprime(i):
print(i)
count += 1
i += 1
Write a python program to accept 10 numbers through command line arguments and calculate the sum of prime numbers among them.
This is my question.
I tried this
for Number in range (1, 101):
count = 0
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count = count + 1
break
if (count == 0 and Number != 1):
print(" %d" %Number, end = ' ')
but this is naive and works only for given range. I want to input 10 numbers in command prompt and it should find the sum of prime numbers in my input. I tried using import sys and giving sys.args[input] but it is showing errors.
Can someone please help with this?I am just starting to learn coding.
Thanks in advance:)
A solution can be this:
import sys
nums = sys.argv
def with_loop():
total = 0 # to collect the prime numbers
count = 1 # a counter for the numbers that you entered
for i in range(10):
num = int(input("{}. Please enter a number: ".format(count)))
if num > 1: # if number is larger than 1, we need to check
for j in range(2, num):
if (num % j) == 0:
break
else:
total += num
elif num == 1: # 1 is a prime number
total += num
else: # otherwise the number is negative so we skip.
pass
count += 1
print("\nTotal : {}".format(total))
def with_argv(nums):
total = 0 # to collect the prime numbers
count = 1 # a counter for the numbers that you entered
for i in range(1, len(nums)):
if int(nums[i]) > 1: # if number is larger than 1, we need to check
for j in range(2, int(nums[i])):
if (int(nums[i]) % j) == 0:
break
else:
total += int(nums[i])
elif int(nums[i]) == 1: # 1 is a prime number
total += int(nums[i])
else: # otherwise the number is negative so we skip.
pass
count += 1
print("\nTotal : {}".format(total))
with_loop()
with_argv(nums)
A simple example:
sum = 0
for count in range(1,11):
sum += int(input(f'Enter number {count} : '))
print(f'Total sum : {sum}')
To solve this problem, I would first define a function that checks whether a number is prime or not. It would only return a Boolean and nothing else.
Then I would create two lists- one for storing all the numbers entered by a user and another for storing all the prime numbers among the numbers entered by the user. I would use my predefined function for this check.
When the list of prime numbers is ready, I would use the sum() method to find the sum of the items of the list viz. the primes numbers the user has entered.
Here is the code-
def isPrime(num): #defining a function to check a given number is prime
factors = []
if num == 2:
return True
else:
for i in range(1, num + 1):
if (num % i == 0):
factors.append(i)
if len(factors) == 2:
return True
else:
return False
numbers = [] #list for user entered numbers
primes = [] #list for prime numbers among them
print("Enter 10 numbers.\n")
for i in range(10):
numbers.append(int(input(f'Enter number #{i + 1}:')))
#adding user inputs to numbers list
for i in numbers: #checking if the entered numbers are prime
if isPrime(i):
primes.append(i)
print("Sum of the prime numbers enters by the user is " + str(sum(primes)))
#sum() method adds all elements in an iterable
This code will do.
Spyder uses IPython Console. That is the command line referred in the question. So, if you run the code in Spyder, the IPython console will run this program.
I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.
My objective of the below code is
check if entered number is a prime
if not print the next biggest prime
def primetest (num):
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting any output.
Time comlexity of your code is O(N) when it find a number which is prime or not.
There is no pointing on dividing from 2 to len(num)-1. It is enough to loop from 2 to sqrt of the given number. Therefore time complexity reduce to O(n) to O(log(n)).
import math
num = int (input ("enter a number:"))
def primeTest(num):
isPrime = 0
for i in range(2,int(math.sqrt(num)+1)):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print(num, "is a prime number")
else:
num = num + 1
repeatTest(num)
def repeatTest (num):
isPrime = 0
for i in range(2,int(math.sqrt(num))):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print("Next Prime: ", num)
else:
num = num + 1
repeatTest(num)
primeTest(num)
The logic which you are using to find if a number if prime seems wrong .
Taking a integer like 9 prints "9 is a prime number" .
And also you are checking for next prime numbers from 2 to Num .
Num being the input , you cant get a number greater than that .
It exits from the loop without even getting in , therefore not printing anything when you are searching for next prime .
You need to change the logic .
write a separate function for checking prime and end the loop when you find the next prime number instead of stopping at num .