-7

0,1,3,6,10,15,21,... each term gets incremented in the order of natural numbers I tried to generate the nth of the series but ended with TLE here's my code

s=0
for(int i=1;i<=n;i++)
    s=s+(i-1);

Can any anybody help me with a better algorithm.

Surya Pranav
  • 1
  • 1
  • 2
  • 9
    Hint: The Nth term in the series can be calculated directly, without any looping whatsoever. In fact, Googling the series will take you to a wikipedia page about the series that gives the exact equation for doing this. – Mooing Duck Sep 10 '14 at 19:28
  • 1
    Searching [specifically on OEIS](https://oeis.org/search?q=1%2C3%2C6%2C10&language=english&go=Search) is useful for identifying well-known integer sequences. – David Eisenstat Sep 10 '14 at 19:53

2 Answers2

2

Think the problem as solving recurrence of the form

T(n) = T(n-1) + n given T(0)=0

T(1) = T(0) + 1

T(2) = T(1) + 2

on solving recurrence you are going to obtain T(n) = n*(n+1)/2

akashchandrakar
  • 2,009
  • 3
  • 23
  • 47
1

This series, gives for n the sum of the natural number from 0 to n. There is a simple formula for calculating this (n * (n+1)) / 2.

Gustavo Torres
  • 464
  • 6
  • 22