Compute the Number Spiral Diagonals

  • 时间:2020-10-11 15:48:46
  • 分类:网络文摘
  • 阅读:138 次

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

It can be verified that the sum of the numbers on the diagonals is 101.

What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

Sum of Number Spiral Diagonals

It is easy to observe that the sum of spiral diagonals are in groups of four: 1, (3, 5, 7, 9), (13, 17, 21, 25) … And the step is incremented by two and we know the last number is the top right corner and its value is N*N if N is the size of the spiral matrix (either row and column).

Thus, we can simulate the process by adding the four numbers and increment the step every four numbers.

1
2
3
4
5
6
7
8
9
10
11
12
function computeSumOfSpiralDiagonals(n) {
  const last = n*n;
  let sum = 1, d = 2, k = 0;
  for (let i = 3; i <= last; i += d) {
      sum += i;
      k ++;
      if (k % 4 == 0) {
          d += 2;
      }
  }
}
console.log(computeSumOfSpiralDiagonals(1001));
function computeSumOfSpiralDiagonals(n) {
  const last = n*n;
  let sum = 1, d = 2, k = 0;
  for (let i = 3; i <= last; i += d) {
      sum += i;
      k ++;
      if (k % 4 == 0) {
          d += 2;
      }
  }
}
console.log(computeSumOfSpiralDiagonals(1001));

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
南方黑芝麻糊大肠菌群超标 5批次产品不合格  烹饪技巧之烹调鸡蛋过程中的常见错误  全新认识冬季当家菜大白菜的营养价值  那些被人们误传的补充某种营养的食物  阿胶产品乱象:原料中被混入骡皮马皮  时令水果橘子橙子柚子营养价值大比拼  中医食疗:滋阴固肾的6款经典补粥  美味鸭肉的保健功效与养生食用方法  让枸杞中的营养成分吸收更好的吃法  多吃葱蒜少吃腌制食品防止胃病癌变 
评论列表
添加评论