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
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?
SOLUTION
Starting from the middle element if we add 2
1+2=3
3+2=5
5+2=7
7+2=9
Now if we start adding 4 and proceed same way 4 times we will get next 4 elements than take six and go on you will get the result.
This is because each cycle increases two elements in a row and column and there will be 4 diagonal elements so we add an elements 4 times.
C CODE:
#include<stdio.h>static int a[5][5];
main()
{
int i=1,j;
int res=1;
int k=1,m=2;
while(k<=500)
{
for(j=0;j<4;j++)
{
i=i+m;
res=res+i;
}
m=m+2;
k++;
}
printf("%d",res);
}
TIME TAKEN
9ms
RESULT
669171001
No comments:
Post a Comment