-2

I want to find the number of the perfect numbers in a range. This is what i have done so far.

#include <iostream>

using namespace std;

int main()
{
   // cout<<"Hello World";
   int sum = 0;
   int count = 0;
   int x,y;
   cout<<"Enter the first number";
   cin>> x;
   cout<<"Enter the second number";
   cin>>y;
   for(int i=x;i<=y;i++)
   {
       for(int j=1; j<i; j++)
       {
           if(i%j == 0)
           {
               sum=sum+j;
           }
       }
       if(sum == i)
       {
           count++;
       }
   }
   cout<<"The number of pefect numbers are: "<<count;


}

However when i enter ranges, it gives me that the number of the perfect numbers available within for example the range of 1 - 10 is 0.

Why is that? I can't figure out what is wrong here?

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160

1 Answers1

2

Need to make sum=0 for every input. For e.g

if(sum == i) {
      count++;
}
sum = 0; /* add this line here */

Or

for(int i=x;i<=y;i++) {
        sum = 0; /* or make sum as 0 here  */
        for(int j=1; j<i; j++) { 
                if(i%j == 0) {
                        sum=sum+j;
                }
        }
        if(sum == i) {
                count++;
        }
}

Also read Why is “using namespace std” considered bad practice?

Achal
  • 11,821
  • 2
  • 15
  • 37
  • 3
    Or even better, put it in the for loop and not as a "global" variable. – Matthieu Brucher Oct 29 '18 at 17:25
  • 1
    @AspiringLilly Also read [Why is “using namespace std” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Achal Oct 29 '18 at 17:34