Connell sequence in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n, we have to find the nth term of Connell sequence. The Connell sequence is as follows: 1. Take first odd integer: 1 2. Take next two even integers 2, 4 3. Then take the next three odd integers 5, 7, 9 4. After that take the next four even integers 10, 12, 14, 16 And so on.

So, if the input is like 12, then the output will be 21

To solve this, we will follow these steps −

  • i := 1
  • while quotient of (i *(i + 1) / 2) < n + 1, do
    • i := i + 1
  • idx := i *(i + 1) / 2, take only quotient
  • num := i^2
  • return num - 2 *(idx - n - 1)

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n):
      i = 1
      while (i * (i + 1) // 2) < n + 1:
         i += 1
      idx = i * (i + 1) // 2
      num = i**2
   return num - 2 * (idx - n - 1)
ob = Solution()
print(ob.solve(12))

Input

12

Output

21
raja
Published on 22-Sep-2020 11:05:11
Advertisements