user5896534
user5896534

Reputation: 113

In general, what is the best way to increment by an increasing sequence of every positive integer?

For example, I first increment from 1 to 2 by n=1, then from 2 to 4 by n=2, then from 4 to 7 by n=3, then from 7 to 11 by n=4, etc. How do I set up my code for an increment such as the one I just prescribed?

I've tried i=1; i+=i, but that just increases by an increasing sequence of positive even integers

Upvotes: 0

Views: 94

Answers (3)

wellplayed
wellplayed

Reputation: 1048

I'm not sure of the application, but here is another way to do it along the lines of what @ruakh said:

i = 1
j = range(100)
for n in j:
    i += n
    print i

Lol, or exactly like what @ruakh said:

i = 1
n = 0
while i < 100:
    i += n
    n += 1
    print i

Upvotes: 1

shx2
shx2

Reputation: 64318

Here is a simple generator function which does this:

def gen_inc():
     n = 1
     inc = 1
     while True:
         yield n
         n += inc
         inc += 1

for n in gen_inc():
     if n > 30: break
     print(n)

1
2
4
7
11
16
22
29

Of course, you can also use the closed-form formula:

def gen_inc():
     n = 1
     while True:
         yield 1+(n+1)*n/2
         n += 1

Upvotes: 2

ruakh
ruakh

Reputation: 183436

You should use two variables: one to track the n that you refer to (which increases by 1 each time), one to track your desired sequence (which increases by n each time).

Upvotes: 0

Related Questions