lundi 4 février 2019

While loop not exiting even though it should

I've written some code but the while loop doesn't exit?

#include <iostream>

#define TriangleNumber(x) (x * (x + 1)) / 2

int main(int argc, char* argv[])
{
    int idx       = 0;
    int n_factors = 0;
    int triangle_num = 0;
    while (n_factors < 3)
    {
        int n_factors    = 0;
        triangle_num = TriangleNumber(idx);
        for (int i = 1; i <= triangle_num; i++)
        {
            if (triangle_num % i == 0)
            {
                n_factors++;
            }
        }
        idx++;
    }
    std::cout << "Number with greater than 3 factors = " << triangle_num;
    return 0;
}

Expect to exit at idx = 3 and triangle number 6.

Aucun commentaire:

Enregistrer un commentaire