谢谢, 我正在尝试解决项目欧拉问题,它希望我打印
Thank you , i am trying to solve a project euler problem it wants me to print the sum of
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这是从数字1开始并按顺时针方向向右移动5 x 5矩阵形成的,但是我在编写螺旋矩阵代码时遇到了麻烦!
this is formed by starting with the number 1 and moving to the right in a clockwise direction for a 5 by 5 matrix but i am in trouble writing a code for the spiral matrix !!
推荐答案强烈建议您自行完成项目Euler问题并寻求帮助,如果您确实遇到困难
It is Highly recommended to do project Euler problems on your own and ask for help if you are really stuck
这是我将如何在c中编写代码以打印问题中建议的螺旋
here is how i will write a code in c to print a spiral as suggested in the question
#include<stdio.h> main() { int i,j,nq=9;//nq is a odd number which represents the order of the matrix int lim=(int)nq/2,cnt=2; int a[nq][nq]; for(i=0;i<nq;i++){ for(j=0;j<nq;j++) a[i][j]=0; } a[lim][lim]=1; a[lim][lim+1]=2; int i1=lim,j1=lim+1;i=lim,j=lim; while(1){ if(cnt>(nq*nq)) break; cnt++; if(i==i1) { j=j1; if(i<=lim) { i=i1; if(a[i1+1][j1]==0) a[++i1][j]=cnt; else a[i1][++j1]=cnt; } else { i=i1; if(a[i1-1][j1]==0) a[--i1][j1]=cnt; else a[i1][--j1]=cnt; } } else { i=i1; if(j<lim) { j=j1; if(a[i1][j+1]==0) a[i1][++j1]=cnt; else a[--i1][j1]=cnt; } else { j=j1; if(a[i1][j1-1]==0) a[i1][--j1]=cnt; else a[++i1][j1]=cnt; } } } for(i=0;i<nq;i++){ for(j=0;j<nq;j++) printf(" %d ",a[i][j]); printf("\n"); } }我用Google搜索了您的问题 projecteuler/problem=28 这也可以解决通过利用其数学性质,请注意
I Googled your question projecteuler/problem=28 this can also be solved by taking advantage of its mathematical nature note that
右上角为n ^ 2 其他角可以显示为n ^ 2-2n + 2,n ^ 2-n + 1和n ^ 2-3n + 3.您只需要总结这些角点
Top right corner is n^2 and other corners can be shown to be n^2-2n+2 ,n^2-n+1, and n^2-3n+3. you just need to sum those corners which comes to be
= 4 * n ^ 2-6 * n + 6
因此,可以通过将第二个数字从1001迭代到3来计算最终答案
hence the final answer can be calculated by iterating over every second number from 1001 to 3
long int sum(int n){ long int sum=1; while(n>1){ sum=sum+4*n*n-6*n+6; n=n-2; } return sum; }更多推荐
如何以螺旋顺序打印数字?
发布评论