I wrote a program, which takes 10 integers from user, and then counts the prime numbers in it and displays the sum. The problem is that it is taking all odd numbers as prime numbers,I have tried very long but couldn't figure it out. plz help me. Here is the program.
#include<iostream>
#include<conio>
#include<math>
int isPrime(int);
int main()
{
int sum_of_prime;
int count=0;
int a[10];
for(int i=1; i<=10; i++){
cout<<"Enter a number: ";
cin>>a[i];
if( isPrime(a[i]) ){
sum_of_prime+=a[i];
countp++;}
}
cout<<"Total Prime Numbers in given Numbers: "<<count<<endl;
cout<<Sum of All the prime numbers in given numbers<<sum_of_prime<<endl;
getch();
}
Think about the logic for a minute. What does your function do? It "proves" primality by disproving divisibility of all values lower than itself. Or, the other way around: it tries to disprove primality by finding a single value that evenly divides 'n'.
The key words here are:
-Disprove by single value.
-Prove by all values.
Your code should reflect this all/single behavior.
You are struggling to understand the algorithm. Here is a much simpler algorithm to test a number for being prime.
Get input number.
See if input%(input-1)==0. If yes, not prime. If no, keep going.
See if input%(input-2)==0. If yes, not prime. If no, keep going.
See if input%(input-3)==0. If yes, not prime. If no, keep going.... and keep going until
See if input%(2)==0. If yes, not prime. If no, input is prime.
This algorithm is wrong. You set the value of b every time. What's the point? Only the very last time will count. Looks like you're trying to set b=0 when you've discovered the number is not prime; why would you then set it back to b=1 on the next time around?