Question:
Problem : I am given the number n
as input, the fact is that this number can be obtained as follows: Let's take the initial value x
, the next value x + 1
, the next x + 2
and so on.
x
is a natural number, that is, the minimum value of x = 1
If we add x + (x + 1) + (x + 2) + ... x + m
alternately, then it is guaranteed that someday we will get n
, the main problem is that the number of such terms is unknown ((The task is in the fact that you need to find the minimum value of x
at which this task will be completed (I repeat – it will be guaranteed that it will be executed)
For this, I could not deduce the math and wrote an overkill:
n = int(input())
nold = n
i = 0
iold = i
x = 1
xold = x
while True:
n = n - (x + i)
i += 1
if n < 0:
i = 0
x = xold + 1
xold = x
n = nold
elif n == 0:
break
print(x)
But, as I expected, the program is too slow with large numbers, can you help? It would be nice if you could help me figure out the math
Answer:
n = 35 # 48, 50
# ax + c = n
a = 1
x = 0
c = 0
a_i = 1
c_i = 0
while (n - c) / a >= 1:
if ((n - c) / a).is_integer():
a_i = a
x = (n - c) // a
c_i = c
c += a
a += 1
if c != 0:
print(' + '.join([str(x)] + ['({0} + {1})'.format(x, coeff) for coeff in range(1, a_i)]), '=', n)
else:
print(x, '=', n)
# 2 + (2 + 1) + (2 + 2) + (2 + 3) + (2 + 4) + (2 + 5) + (2 + 6) = 35
# 8 + (8 + 1) + (8 + 2) + (8 + 3) + (8 + 4) = 50
# 15 + (15 + 1) + (15 + 2) = 48
Another option :
import math
n = 3 # 34, 36, 1569
c = int(math.sqrt(n)) + 1
a = c + 1
c_n = sum(range(1, a))
if c_n == n:
x = 1
else:
x = n
for c_i in range(c, 0, -1):
if ((n - c_n) / (c_i + 1)) % 1 == 0:
c = c_i + 1
x = (n - c_n) // c
break
c_n -= c_i
if c != 0:
print(' + '.join([str(x)] + ['({0} + {1})'.format(x, c_i) for c_i in range(1, c)]), '=', n)
else:
print(x, '=', n)
# 1 + (1 + 1) = 3
# 7 + (7 + 1) + (7 + 2) + (7 + 3) = 34
# 1 + (1 + 1) + (1 + 2) + (1 + 3) + (1 + 4) + (1 + 5) + (1 + 6) + (1 + 7) = 36
# 259 + (259 + 1) + (259 + 2) + (259 + 3) + (259 + 4) + (259 + 5) = 1569