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

编程入门 行业动态 更新时间:2024-10-27 19:23:02
本文介绍了如何以螺旋顺序打印数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

谢谢, 我正在尝试解决项目欧拉问题,它希望我打印

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; }

更多推荐

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

本文发布于:2023-08-07 06:59:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1317628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:螺旋   顺序   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!