且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以螺旋顺序打印数字?

更新时间:2023-02-11 16:18:11

强烈建议您自行完成项目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搜索了您的问题 http://projecteuler.net/problem=28 这也可以解决通过利用其数学性质,请注意

I Googled your question http://projecteuler.net/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;
    }