problem with if

it dose not work !! the program must determine if the number is perfect or not

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 #include<iostream>

using namespace std;
int main ()
{
	int a,b,c=0;
	cout<<"please enter a postive number "<<endl;
	cin>>a;
	b=1;
	while(b<=a){


		if(a%b==0)
			c=c+b;
		b++;
	}
	if(c==a)
		cout<<"perfect"<<endl;
	else if (c!=a)
		cout<<"not"<<endl;
	
	
	system("pause");
	return 0;
}
	
closed account (o3hC5Di1)
Hi there,

Your problem is here:

while(b<=a){

a divided by itself will return a remainder of 0. so it will be added to the total as well. This should be a quick fix:

while(b<a){

Additionally, you can do some optimization: you don't need to check up to the actual number. Checking until a/2 will be faster and should suffice.

All the best,
NwN
thanks alot my friend
Topic archived. No new replies allowed.