Handling large numbers python 2.7 (runtime error)

I need to create a program that finds the nth element in the following infinite sequence:

1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1......

So, you can see that the increments of the "center" by one and the side elements of the "center" reflect each other, so we can break this sequence into small groups:

[1][121][12321][1234321]..... 

So, the task is to find the nth element in the sequence n. For example, we take 7 as input and should return 3 because the seventh element in the sequence is 3. The problem here is that when n exceeds 10^15, my program shows a runtime error, while the input may be like 10^100000. Here is my code:

n = int(input())
fin = n
number = long(1)
counter = long(0)
while n>0:
    n = n - number
    number = number+2
    counter = counter + 1
mid = long((counter-1)*(2+2*(counter-1))/2+1)

place = long(counter - abs(mid-fin))

if fin==0:
    print 0
else:
    print place
+4
source share
1

:

[1] [1 2 1] [1 2 3 2 1] ...

k:

1 + 3 + 5 + ... + k*2-1 

,

(1 + k*2-1) * k / 2 = k^2

k, n- .

k = ⌊sqrt(n-1)⌋

, n- k+1, k*2+1. k ( k^2 ), n-k^2. k+1 - |n-k^2 - (k+1)|. n :

n = int(input())
k = int(math.sqrt(n-1))
print(k+1 - abs(n-k*k - (k+1)))

, n <= 10^5000000, math.sqrt, . SO .

+7

Source: https://habr.com/ru/post/1691683/


All Articles