Writing a function to find a triangular number in python 2.7 -
i couldn't find answer searching , i've been working on 2 days , stumped. think confused on math. trying write function finds first n triangular numbers.
def formula(n): = 1 while <= n: print i, '\t', n * (n + 1)/ 2 += 1 print
so example if type in formula(5) this:
1 1 2 3 3 6 4 10 5 15
i got how make table going 1 through whatever number choose n.. can't figure out how make second part equal formula typed in n*(n+1)/2. logic going through this? everytime type in formula(5) example loop goes 1-5 returns same exact answer in right hand column way down 15. can't make start @ 1, 3, 6 etc on right hand side.
the comment observed computing n * (n + 1) / 2
instead of i * (i + 1) / 2
correct. can rid of having multiplication , division @ each step observing i-th triangle number sum of integers 1 i, @ each step have add previous triangle number. code below:
def formula(n): ith_sum = 0 in xrange(1, n+1): ith_sum += print i, '\t', ith_sum
Comments
Post a Comment