Description
萌萌哒cy学姐参加去年的新生杯的时候,蛇形矩阵那题被她分分钟秒掉,于是她决定出一个更难的题目,她要求矩阵里的每个数都是质数,当然,蛇形的规则也略有变化
如2*3矩阵:
2 7 11
3 5 13
再如3*4的矩阵
2 13 17 37
3 11 19 31
5 7 23 29
Input
第一行为一个正整数T,表示数据的组数,接下来T行,每行两个正整数n,m,表示矩阵有n行m列
Output
对于每一个输入输出n行,每行m个数,表示这个矩阵,输出内容见题目描述,每个数输出宽度为6
Sample Input
2
2 3
3 4
2 3
3 4
Sample Output
2 7 11
3 5 13
2 13 17 37
3 11 19 31
5 7 23 29
3 5 13
2 13 17 37
3 11 19 31
5 7 23 29
Hint
1<=n,m<=100
超时代码:哭晕
#include<stdio.h>
#include<string.h>
#include<math.h>
int zhi(int num)
{
int i,j,p,h=;
static int k=;
for(i=k;;i++)
{
int p=sqrt(i);
for(j=;j<=p;j++)
{
if(i%j==)
break;
}
if(j<=p)
continue;
k=i+;
return i;
}
}
int main()
{ int a[][];
int m,n,x,y;
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&m,&n);
{
memset(a,,sizeof(a));
int count=;
a[x=][y=]=;
while()
{
while(!a[x+][y]&&x+<m)
a[++x][y]=zhi(++count);
while(!a[x][y+]&&y+<n)
a[x][++y]=zhi(++count);
while(!a[x-][y]&&x->=)
a[--x][y]=zhi(++count);
while(!a[x][y-]&&y->=)
a[x][--y]=zhi(++count);
if(count==m*n-)
break;
}
for(x=;x<m;x++)
{
for(y=;y<n;y++)
printf("%6d",a[x][y]);
printf("\n");
}
}
} }
AC代码
#include<stdio.h>
#include<string.h>
#include<math.h>
int b[];
int z()//求素数
{
int i,j,count=;
for(i=;;i++)
{
int k=sqrt(i);
for(j=;j<=k;j++)
{
if(i%j==)
break;
}
if(j<=k)
continue; b[count]=i;
count++;
if(count==)
break;
}
}
int main()
{ int a[][];
int m,n,x,y;
int T;
scanf("%d",&T);
z();
while(T--)
{
scanf("%d%d",&m,&n); memset(a,,sizeof(a));
int count=;
a[x=][y=]=;
while(count<m*n-)
{
while(!a[x+][y]&&x+<m)
a[++x][y]=b[++count];
while(!a[x][y+]&&y+<n)
a[x][++y]=b[++count];
while(!a[x-][y]&&x->=)
a[--x][y]=b[++count];
while(!a[x][y-]&&y->=)
a[x][--y]=b[++count];
}
for(x=;x<m;x++)
{
for(y=;y<n;y++)
printf("%6d",a[x][y]);
printf("\n");
} } }