Need help converting iterative pattern into formula
-
13-09-2019 - |
Question
var = 8
itr 1:
var == 8 (8 * 1)
itr 2:
var == 24 (8 * 3)
itr 3:
var == 48 (8 * 6)
itr 4:
var == 80 (8 * 10)
itr 5:
var == 120 (8 * 15)
Pattern: (var * (last multiplier + current iteration))
Basically I want to get the result of formula(itr) without having to iterate up to itr.
Solution
The value of var
in the nth
iteration is 8 times the sum of 1..n. The sum of 1..n is given by the formula (n)(n+1)/2
; for example, the sum from 1..6 is 6*7/2 = 21.
Thus, var == 4(i)(i+1)
on the ith
iteration.
OTHER TIPS
Use triangular numbers.
Multiply 8 by the sum of 1 to the current iteration:
>>> def itr(n): return 8 * sum(xrange(n+1))
...
>>> itr(1)
8
>>> itr(2)
24
>>> itr(3)
48
>>> itr(4)
80
>>> itr(5)
120
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow