Difficulty with triangular number program [duplicate]

0

I'm having trouble creating a program that prints if the number you typed is triangular or not. How do I proceed to create an indefinite sequence for a large number within the conditional?

#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;
}
    
asked by anonymous 20.04.2015 / 03:01

1 answer

2

This case is very easy and basic. For a number to be triangular it must be a finite sum. So the finite "subtraction" has been zero.

You can loop through recursion :

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, you can also use the formula (n² + n) / 2 to your " favor "and calculate the square root of the possible equation. Of the two results, one is eliminated (negative) and another may be accurate or inaccurate. If it is accurate, it is triangular.

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

    
20.04.2015 / 04:30