Question

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?

Was it helpful?

Solution 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;    
}

OTHER TIPS

  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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top