Is there a formula to get the solution in the picture without using a repeat statement?

Asked 2 years ago, Updated 2 years ago, 48 views

I'm asking you this question because I want to save time while solving algorithm problems!

When numbers are listed in a picture-like rule, is there a formula that allows you to figure out what number an arbitrary number is on the left without writing a repetition?

For example, I would like to know if there is a formula that gives 8 when I enter 31!

algorithm

2022-09-22 08:39

1 Answers

Sn = 1, 3, 6, 10, ... (number on the top row of stairs)

S1 = 1, S2,= 3, ... A well-known sum of 1 to n. Sn = n(n+1)/2

Tn = 1, 2, 4, 7, ... (the bottom row numbers in the picture)

Tn = S(n-1)+1 = n(n-1)/2 + 1 = (n^2 - n + 2)/2

Given x, the desired n is

>>> def n(x):
    return int((1+(8*x-7)**.5)/2)

>>> for i in range(1, 32):
    print(i, n(i))


1 1
2 2
3 2
4 3
5 3
6 3
7 4
8 4
9 4
10 4
11 5
12 5
13 5
14 5
15 5
16 6
17 6
18 6
19 6
20 6
21 6
22 7
23 7
24 7
25 7
26 7
27 7
28 7
29 8
30 8
31 8


2022-09-22 08:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.