calculate the number of times a value needs to shift to complete 1 full cycle

77 Views Asked by At

How can I calculate the number of times I will need to shift increment a "square" loop so that 1 full repeated cycle is completed?

Image of a of 5 by 6 array requires an increment of 1-91 for 1 full cycle 1 full cycle 1-91

Example: of a 5 by 6 array

First "square" loop (which follows the green dot 18 shift increments are needed to complete 1 "square" loop cycle) 1 2 3 4 5 6 12 18 24 30 29 28 27 26 25 19 13 7

Second "square" loop (which follows the yellow dot 10 shift increments are needed to complete 1 "square" loop cycle) 8 9 10 11 17 23 22 21 20 14

Third "square" loop (which follows the orange dot 2 shift increments are needed to complete 1 "square" loop cycle) 15 16

Static image and start of loop

Start of loop

Example:

For the 1st outer square Loop (which follows the green dot it takes 90 increments or 5 "square" loop cycles to complete 1 full cycle

For the 2nd square Loop (which follows the yellow dot it takes 90 increments or 9 "square" loop cycles to complete 1 full cycle

For the 3rd square Loop (which follows the orange dot it takes 90 increments or 45 "square" loop cycles to complete 1 full cycle

How can I calculate the number of times I will need to shift increment a "square" loop so that 1 full repeated cycle is completed? The reason I ask is because I want to calculate these values for other m x n arrays

Animated image of square loops 1-91 this completes 1 full cycle

Animated full loop

1

There are 1 best solutions below

1
On BEST ANSWER

For an $m\times n$ array, the length of the $k$-th loop is $$4+2m+2n-8k=2(2+m+n-4k),$$ where $k=1$ corresponds to the outer loop. The total number of shifts needed is then the least common multiple of these lengths, where $k$ runs from $1$ to $\ell:=\min\{\lceil\tfrac m2\rceil,\lceil\tfrac n2\rceil\}$. That is, your number is $$2\cdot\operatorname{lcm}\left\{2+m+n-4k: 1\leq k\leq\ell\right\}.$$ As for how to compute this number effectively; I do not know if there is a simple expression, but for small $m$ and $n$ (let's say $m,n<1000$) a computer can compute this quite quickly. For example, here is a piece of Python code that will do the trick:

def gcd(a,b):
  if b == 0:
    return a
  else:
    return gcd(b,a%b)

def lcm(a,b):
  return a*b//gcd(a,b)

def NumberOfShifts(m,n):
  N = 1
  l = min(-(-m//2),-(-n//2))
  for k in range(1,l):
    N = lcm(N,2+m+n-4*k)
  return 2*N

m=5
n=6
print(NumberOfShifts(m,n))