Chinaunix首页 | 论坛 | 博客
  • 博客访问: 239218
  • 博文数量: 47
  • 博客积分: 1229
  • 博客等级: 中尉
  • 技术积分: 568
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-20 10:06
文章分类

全部博文(47)

文章存档

2014年(1)

2013年(7)

2012年(1)

2011年(38)

分类: C/C++

2011-03-21 21:18:47

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?
--------------------

  1. #include <stdio.h>

  2. #define N 1001/2


  3. int main(int argc, const char *argv[])
  4. {
  5.     int    sum = 1;
  6.     int i;

  7.     for (i = 1; i <= N; i++)
  8.         sum += 4*(2*i+1)*(2*i+1) - 12*i;

  9.     printf("sum: %d\n", sum);

  10.     return 0;
  11. }

注意N在某值时可能导致溢出。

阅读(2447) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~