Need Help here!!

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();
}

int isPrime(int n){
for(int i=2; i<=sqrt(n); i++){
if(n%i==0)
return 0;
else
return 1;}
}
1
2
3
4
5
for(int i=2; i<=sqrt(n); i++){
if(n%i==0)
return 0;
else
return 1;}


Here is what your for loop does:

if(n%i==0): if the number is even (because i=2)... return 0;
otherwise, return 1

Your for loop does not repeat at all.
Last edited on
Okay I got it. But what should i do now... I am still not getting the right answer........ :(
But what should i do now


You should fix your code so it works.
can you give a hint?
Fix your algorithm.
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.
I am not getting it. Can you plz explain it a bit...... its 3hrs since i have been thinking on it.....

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.
i have done upto here , but its still wrong.

int isPrime(int n){
int b=1;
for(int i=2; i<=sqrt(n); i++)
{if(n%i==0)
b=0;
else
b=1;}
if(!b)
return 0;
else
return 1;
}
1
2
3
4
5
for(int i=2; i<=sqrt(n); i++)
{if(n%i==0)
b=0;
else
b=1;}


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?
Last edited on
int isPrime(int n){
for(int i=2; i<=sqrt(n); i++)
{if(n%i==0)
return 0;
}
return 1;

}

IS this right ?
Yep, now you've got it.
Topic archived. No new replies allowed.