1

I was wondering how to develop a C++ program that prompts the user for 2 numbers n1, n2 with n2 being greater than n1. Then the program is meant to determine all the perfect numbers between n1 and n2. An integer is said to be a perfect number if the sum of its factors, including 1 (but not the number itself), is equal to the number itself. For example, 6 is a perfect number because 6 = 1 + 2 + 3.

so far here is what I have come up with, and it has no runtime/syntax errors, but unfortunately logical error(s):

#include <iostream>
using namespace std;

int main(){
    int number, sum = 0, divi = 1, n1, n2;
    cout<<" Please enter n1: ";
    cin>>n1;
    cout<<" Please enter n2: ";
    cin>>n2;
    number = n1;
    while(number <= n2){

        while(divi <=n2){

            if (number%divi ==0)
                sum+=divi;

            divi++;
        }

        if(sum == number) 
            cout<<number<<endl;

        number++;
    }
    return 0;    
}

I can only use while loops. Can you spot any logical errors?

false
  • 10,264
  • 13
  • 101
  • 209

2 Answers2

3
  1. You need to reset divi to 1 and sum to 0 just after the line while(number <= n2){. (Otherwise divi and sum will grow in error).

  2. Redefine the upper bound of your inner while to while(divi < number){. (You want to examine the factors between 1 and number, not after it.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2
#include <iostream>
using namespace std;

int main(){
int number, sum = 0, divi = 1, n1, n2;
cout<<" Please enter n1: ";
cin>>n1;
cout<<" Please enter n2: ";
cin>>n2;
number = n1; 
while(number <= n2){
    sum=0;   // reintialize variable for every incrasing number n1 to n2
    divi=1;  // reintialize variable
    while(divi <number){ //use number insteaed of n2

        if (number%divi ==0)
        {
            sum+=divi;
        }
        divi++;
    }

    if(sum == number) 
        cout<<number<<endl;

    number++;
}
return 0;    
}
Rishi Dwivedi
  • 908
  • 5
  • 19
  • 1
    Not much of an answer from what I can see... Could you add an explanation so it is clear to those who are viewing your post? – David G Mar 13 '14 at 13:13
  • 1
    Good, but I meant you shouldn't just post the code by itself. It's always good to make a short summary of the changes you made and why they helped. – David G Mar 13 '14 at 13:19
  • Thank you so much for this. The comments were very helpful and it executed exactly as I wanted! – user3311681 Mar 13 '14 at 18:56