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.
Related
Write a python script to print all Prime numbers between two given numbers (both values inclusive)
can anyone please tell what am I doing wrong here ?
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
for i in range(2,k):
if k%i!=0:
if k!=i:
continue
elif k==i:
print(k)
break
elif k!=i:
break
you are checking if a number is prime the wrong way there are many
unhandled cases in your code for example if a is larger than b
you will start looping from "a" anyway
and even if the values are sat up correctly the algorithm is not right
here is my optimal solution hope it will help
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
def is_prime(n):
# negative numbers cannot be primes 1 and 0 are also not primes
if n <= 1:
return False
# since 2 is the first prime we will start looping from it
# until n since you mentioned that n is included
for i in range(2, n + 1):
# if n is cleanly divisible by any number less than n
# that means that n is not prime
if n % i == 0 and n != i:
return False
return True
for k in range(a,b):
if a > b:
print ("a cannot be bigger than b")
if is_prime(k):
print(k)
Here's the solution. I added some comments to explain what the code does.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
# Include b in the range by adding 1
for num in range(a, b + 1):
# Prime numbers are greater than 1
if num > 1:
for i in range(2, num):
# If the number is divisible, it is not prime
if num % i == 0:
# Check if the number is equal to the number itself
if num != i:
break
else:
# If the loop was not broken, the number isn't divisible
# by other numbers except itself and 1, so it's prime
print(num)
Well, a prime is "a number that is divisible only by itself and 1", so to actually first I would go only to range(2, k-1). This approach you have is one of the most straightforward ways of doing it, and is not computationally friendly. There are algorithms that specialize in this kind of prime number finding.
I have fixed the code, simplifying the expressions and adding like already mentioned +1 for inclusivity.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b+1):
for i in range(2,k+1):
if k==i:
print(k)
elif k%i!=0:
continue
else: # is divisible and isn't 1 or the number
break
I encourage you to see this post, how they do it.
An other way of doing it would be:
#Check only 1 number at time:
def check_prime(check):
if check > 1:
for i in range(2, check):
if check % i == 0:
return False
return True
return False
#then check your numbers in a loop
list_prime = []
for i in range(50, 250):
if check_prime(i):
list_prime.append(i)
print(list_prime)
That way you can check 1 possible prime number at time.
If you need numbers in between just put it in loop.
Usually, when generating prime numbers utilizing some form of the "Sieve of Erotosthenes" algorithm, it is only necessary to check for denominator values up to the square root of the number being evaluated. With that in mind, here is one more possible take on your prime number loop test.
import math
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
if k == 2 or k == 3: # Pick up the prime numbers whose square root value is less than 2
print(k)
x = int(math.sqrt(k) + 1) # Need only check up to the square root of your test number
for i in range(2,x):
if k%i!=0:
if x-1 > i:
continue
else:
print(k)
else: # If the remainder is zero, this is not a prime number
break
Another version to try.
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)
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 .
I'm trying to write a program in python that can either print 1 through nth numbers of the prime number sequence, or print just the nth number of the prime number sequence. Here is the code.
import math
P = 2
X = raw_input('Choose a number: ')
Y = 1
def prime(P, Y):
Choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
if Choice == "1":
while Y <= int(X):
isprime = True
for x in range(2, int(P) - 1):
if P % x == 0:
isprime = False
break
if isprime:
print P
Y += 1
P += 1
elif Choice == "2":
prime(P, Y)
Basically, i have the first part down, so that it prints 1 through nth numbers of the prime sequence. However, I'm quite lost on how to make it calculate just the nth prime, where the nth prime is the given through raw input. It must be possible to do this in python, however, how would it be done, and what would be the best way to do so, without having to add too many new variables that i don't have here, (though i would be fine doing so). Help would be appreciated.
Add a condition so that if either the user wants to print all numbers, or you have reached the final prime number of the sequence, the number will be printed. (I have also replaced some of the variable names with more descriptive ones, and altered it so that the function is passed the number_of_primes as its only parameter, which would seem to make more sense.)
def print_primes(X):
choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
count = 1
n = 2
while count <= X:
is_prime = True
for i in range(2, int(n) - 1):
if n % i == 0:
is_prime = False
break
if is_prime:
if choice == "1" or count == X:
print n
count += 1
n += 1
number_of_primes = int(raw_input('Choose a number: '))
print_primes(number_of_primes)
Just only print if it's the Yth number:
if isprime:
Y += 1
if Y == X:
print P