简体   繁体   中英

Efficient Data structure and Algorithm - Natural Sequence

1 - 1
2 - 2,3
3 - 4,5,6
4 - 7,8,9,10

Given any number from 4 to 6 ,I need the output as 3.

Given any number from 7 to 10 ,I need the output as 4.

I need the fastest solution for the above problem to solve an algorithm.

What I could think of is a brute force algorithm :

Given 7:

n-square + n = 7*2 = 14
1 + 1 = 2  < 14
4 + 2 = 6  < 14
9 + 3 = 12 < 14
16+ 4 = 20 >=14 --> So 4 

Is there any better approach to arrive at the solution ? OR My approach to the algorithm itself is flawed ?

Brief explanation of the algo :

A,B,C

After every iteration every element becomes increased by one.

A,A,B,B,C,C

Given 3, C will be returned.

Given 4 or 5, A will be returned.

Given 6 or 7, B will be returned.

Given 8 or 9, C will be returned.

Given 10 or 11 or 12, A will be returned.

Given 13 or 14 or 15, B will be returned.

How the solution to the mathematical problem will help solve the algo :

Total number of elements = 3

Given number = 13 (Output to be B)

Divide and Ceiling = Ceil (13/3) = 5 [So 13 falls under when every element has become * 3] (From Mathematical problem : If given number is 5, 3 is to be used)

Starting index of when every element has become * 3 [IS_EQUAL_TO = ] 3 * 3(summation of previous iteration => 1 + 2) + 1 = 10

To Find the index = Ceil(13-10+1/3 (this 3,comes from the mathematical problem) ) = Ceil (4/3) = 2nd index = B

Given number of rows N, the size of the triangle is N(N+1)/2. You are essentially trying to find the least integer N such that N(N+1)/2 >= M, with M given. If you have a function to compute square roots, you can solve this equation in constant time.

N(N+1)/2 >= M, multiply both sides with 2,
N²+N >= 2M, complete the square, take the square root, blablabla
N >= sqrt(2M+1/4)-1/2

Therefore the answer is N = ceil(sqrt(2*M + .25) - .5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM