Calculating triangular numbers A triangular number is a product of three factors as follows:

$$
\text{Triangular number} = x(x + 1)(x + 2)
$$

Is there a way to make this code faster? As it is the code calculates every triangular number less than or equal to the integer given by the user.

#include &lt;stdio.h&gt;

int main(void) {       

    int firstFactor = 0;
    int secondFactor = 1;
    int thirdFactor = 2;

    int userInput;
    int product = 0;

    printf("Enter a integer: ");
    scanf("%d", &amp;userInput);

    if(userInput == 0) {
        printf("User input is a triangular number\n");
        return 0;
    }

    do {
        firstFactor++;
        secondFactor++;
        thirdFactor++;
        product = firstFactor * secondFactor * thirdFactor;
    } while(product &lt; userInput);

    if(product == userInput) {
        printf("User input is a triangular number\n");
    } else {
        printf("User input is not a triangular number\n");
    }
    return 0;
}
I see a couple of ways to speed this up.

Observe that at least one factor is even, and exactly one factor is a multiple of 3, so these numbers are all divisible by 6. Assuming random input, testing for that at the beginning will find the answer in one inexpensive operation in 5 out of 6 cases:

if (userInput % 6) {
    printf("User input is not a triangular number\n");
    return 0;
}


As for the rest of it, if we set n = x + 1, we get

$$T(n-1)=(n-1)(n)(n+1)=n^3-n$$

Thus, we can solve in O(1) time, though the cube root is a somewhat expensive operation:

#include &lt;math.h&gt;    /* Link with -lm in gcc */

int n;

n = (int) (ceil(cbrt(userInput)) + 0.1);
if (n * (n-1) * (n+1) == userInput)
    printf("User input is a triangular number\n");
else
    printf("User input is not a triangular number\n");


We add 0.1 after the ceil because the double value might be something like 6.9999999999759, which would round to the wrong number when converted to int. The (int) cast suppresses a compiler warning about conversion from double to int.