Nima Faraji
Nima Faraji

Reputation: 1

Why am I getting an infinite loop (factors)?

The proper divisors of a positive integer, n, are all the positive integers that divide n evenly other than n itself. For example, the proper divisors of 16 are 1, 2, 4, and 8.

An abundant number is an integer greater than 0 such that the sum of its proper divisors is greater than the integer. For example, 12 is abundant because 1+2+3+4+6 = 16 which is greater than 12.

A deficient number is an integer greater than 0 such that the sum of its proper divisors is less than the integer. For example, 8 is deficient because 1+2+4 = 7 which is less than 8.

A perfect number is an integer greater than 0 such that the sum of its proper divisors is equal to the integer. For example, 6 is perfect because 1+2+3 = 6.

enter image description here

#include <iostream>
#include <cctype>
#include <iomanip>
#include <cmath>
using namespace std;

    int main()
    {
      int current;
      int possible;
      int sum=0;
      int facts=0;

      cin >> current;

the current is: 17 -5 246

      while(cin){
        cout << current;
        for (possible=1; possible<= current; possible++)
          {
            if(current%possible==0)
              {
              sum= sum + possible;
              facts++;
             if(sum-current > current)
              cout << "is abundant and has" << facts  << "factors" << endl;
            if(sum-current < current)
              cout << "is deficient" << endl;
            if(current < 2)
              cout << "is not abundant, deficient or perfect" << endl;
            if(current == sum-current)
              cout << "is perfect" << endl;

          }
        }
      }

        return 0;
      }

This is what I should be getting: 17 is deficient -5 is not abundant, deficient or perfect. 246 is abundant and has 8 factors instead I get an infinite loop

Upvotes: 0

Views: 82

Answers (2)

Vishal-L
Vishal-L

Reputation: 1347

The problem is that you are using cin as a condition for while loop, as the loop will continue to execute till there's no more data to be read.

Refer What's the difference between while(cin) and while(cin >> num)

Instead input the current number inside while loop i.e

while(cin >> current){
    /* Your code */
}

Note:

To stop reading input from user in Linux terminal, enter Ctrl+D

And I also see that your logic is not right so you might be getting wrong results, and this you must be solving on your own.

Upvotes: 1

samini
samini

Reputation: 195

You can use int current[3] instead of int current and check receiving end of current array instead of while(cin)

Upvotes: 0

Related Questions