MrLucky2243
MrLucky2243

Reputation: 47

If else statement keeps looping infinetely

#include <iostream>
using namespace std;

int factorial(int n){ //Aprēķina skaitļa faktoriali izsaucot pati sevi
    if(n > 1)
        return n*factorial(n - 1);
    else
        return 1;

}
int main(){
int ok;
do{


  int n;
    cout << "Enter a integer: ";
    cin >> n;
    int x=factorial(n);
    cout << "Factorial=" << x << endl;
    for(int a=1;(a+2)<(x/2+1);a++){ 

       if(a*(a+1)*(a+2)==x)
            cout << "Equals " << a << "*" << a+1 << "*" << a+2 << endl;
        else 
            cout<<"Cant be a multiplication of 3 numbers"<<endl;
    }

    cout << " Do you want to continue (1) or end (0)?" << endl;
    cin >> ok;
}
while (ok==1);
}

So hey I got this code where it has a factorial function and it checks if the factorial can be a multiplication of 3 consecutive numbers

for(int a=1;(a+2)<(x/2+1);a++){ 

           if(a*(a+1)*(a+2)==x)
                cout << "Equals " << a << "*" << a+1 << "*" << a+2 << endl;
            else 
                cout<<"Cant be a multiplication of 3 numbers"<<endl;
        }

I am running into a problem in this part now if I for example enter 8 it gives out the factorial 40320 and infinite spam of "Cant be a multiplication of 3 numbers", ALSO when I enter 1 or 2 it doesnt spam out "Cant be a multiplication of 3 numbers" it just gives out the factorial 1 or 2 Thanks for help in advance!!

Upvotes: 0

Views: 65

Answers (1)

Little Boy Blue
Little Boy Blue

Reputation: 311

You need to add a break; statement after:

cout<<"Cant be a multiplication of 3 numbers"<<endl; 

I believe the issue with entering 1 or 2 is the math in:

int a=1;(a+2)<(x/2+1);a++;

Upvotes: 2

Related Questions