Difficulty with triangular number program

Asked

Viewed 495 times

0

I’m having trouble creating a program that prints whether the number typed is triangular or not. How should I proceed to create within the conditional an undefined sequence for a large number?

#include <stdio.h>

int main (void)
{
    int num, i, aux;
    scanf("%d", &num);

    num = n*(n + 1)/2;

        for(i = 1; i + (i + 1)<=num; i++ )
            {

                if(i + (i + 1) + (i + 2) == num)
                aux = 1;

            }
        if (aux) 
            {
                printf("SIM");
            }
        else
            {
                printf("NAO");
            }   

    return 0;
}
  • The variable aux was not initialized.

1 answer

2

This case is very easy and basic. For a number to be triangular it needs to be a finite sum. Therefore, finite "subtraction" has zero.

You can make a looping by recursiveness:

char triangular(int numero) //Leia-se bool
{
    static unsigned int counter = 1
    if( (numero - counter) == 0 && numero != 1) return 1; //Se a subtração for zero e se o número não for 1
    else if( (numero - counter) < 0) //Caso a subtração for menor que zero (não triangular)
    {
        counter = 0;
        return 0;
    }
    else //Caso a subtração for positiva (há mais o que fazer)
    {
        counter++;
        return triangular(numero + 1 - counter);
    }
}

Or, also, you can use the formula (n² + n) / 2 in its "favor" and calculate the square root of the possible equation. Of the two results, one is eliminated (negative) and the other may be exact or inaccurate. If accurate, it’s triangular.

PS.: The second method is not definitive although it is faster. The first method is more reliable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.