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. 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();
}
int isPrime(int n){
for(int i=2; i<=sqrt(n); i++){
if(n%i==0)
return 0;
else
return 1;
}
}
Your
isPrimemethod returns during the first pass through the loop, and NEVER does subsequent passes through the loop.It checks 2, but never checks 3, 4, 5, 6, etc.
You need to
return 1;ONLY after you’ve run though the entire loop:P.S. For a speed improvement, just check 2, then 3,5,7,9,11, etc.
There is no point in checking all the other even numbers (4,6,8,etc).
So you can run about twice as fast if you only check odd numbers.
You can also improve the speed by not doing a
sqrt(n)on every pass through the loop.This function would look like: