wap to input N different numbers and display the sum of prime number
do this pls
Answers
def is_prime(n):
if n < 2:
return 0
if n <= 3:
return 1
if n % 2 == 0 or n % 3 == 0:
return 0
i = 5
while(i * i <= n) :
if n % i == 0 or n % (i + 2) == 0:
return 0
return 1
nums = list(map(int, input("enter nums: ").split()))
print("sum of primes:", sum([n for n in nums if is_prime(n)]))
Required Answer:-
Question:
- Write a program to input n different numbers and display the sum of prime numbers.
Solution:
This is an easy question.Here is the code.
This is written in Java.
import java.util.*;
public class PrimeSum {
static boolean isPrime(int n) {
int c=0;
for(int i=1;i<=n;i++) {
if (n%i==0)
c++;
}
return (c==2);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("How many numbers?? ");
int n=sc.nextInt(), s=0;
System.out.println("\nEnter the numbers...");
for (int i=0;i<n;i++)
{
System.out.print("Enter: ");
int j=sc.nextInt();
if(isPrime(j))
s+=j;
}
System.out.println("Sum of all the prime numbers is: "+s);
sc.close();
}
}
This is written in Python.
def isPrime(x):
c=0
for i in range(1,x+1):
if x%i==0:
c=c+1
if c==2:
return True
else:
return False
n,s=int(input("how many numbers?? ")),0
print("Enter them...")
for i in range(0,n):
x=int(input("Enter: "))
if isPrime(x):
s+=x
print("Sum of all the prime numbers is: ",s)
★ I have created a function which checks if a number is prime or not. Then, I have taken n numbers as input. If the number entered is prime then it is added to s. The final result of s is the sum of all the prime numbers.
Output is attached.