I was working on a coding problem and as subpart of it I got this problem:
We are given a number x and we square it so number becomes x^2. Now we have numbers from 1 to x^2 e.g:
if number=4;
then
4^2=16
1 ----->1
2 3 ----->2
4 5 6 ----->3
7 8 9 10 ----->4
11 12 13 ----->5
14 15 ----->6
16 ----->7
Now I am given a number say k and I need to tell that to which group it belongs. Here 8 belongs to 4th group.
What I thought is start from 1 and keep count initialized to 1 and check whether 1<8? if yes then add 2 to 1(prev sum),increase count to 2 and check whether 3<8? if yes then add 3 to 3(prev sum),increase count to 3 and check whether 6<8 if yes then add 4 to 6, increase count to 4 and check whether 10<9? if no then exit.
So group no. is count i.e 4.
But is there any fast method than my approach?
EDIT 1:
I forgot to mention that in my algo when count reaches the given number which is 4 in prev example then I should not add 5 but 3. e.g.:
If number to search is 14 then
1<14 yes then add 2
3<14 yes then add 3
6<14 yes then add 4
10<14 yes then add **3** ---->here I need to add 3 instead of 5
13<14 yes then add **2** ---->here I need to add 2 instead of 6
15<14 No so output count.
it is possible to add 3 instead of 5 using if condition but is there any method in which the value to be added automatically increases and then decreases depending on value of x(see example above to know what x refers to)
The upper half of the rectangle is a triangle:
and the numbers on the right side (1, 3, 6, 10) are called triangular numbers. The inverse formula there (under the subtitle “Triangular roots and tests for triangular numbers”) can be used for your problem: