C语言 请高手帮我改一下

来源:百度知道 编辑:UC知道 时间:2024/06/04 14:48:37
题目:输入一个整数n(0<=n<9),请输出满足以下条件的n位正整数的个数:

要求该n位整数的从高位开始前1位可以被1整除,该n位整数前2位可以被2*2整除,该整数前3位可以被3*3整除,该整数前4位可以被4*4整除……。即该整数前k位都可被k平方整除。

请输出符合该条件的n位正整数的数量。

如输入:1,应该输出:9
2 22

我自己写了一个程序,在输入小于5的时候测试都是成功的,输入大于等于5了就会出现错误,不值得错在哪里,请高手帮我看一下!
谢谢了

#include <math.h>
main()
{
int s,n,i,count = 0,t,tmp;
scanf ("%d",&n);
for (s = pow (10,n - 1);s < pow (10,n);s++)
{
t = 1;
tmp = pow (10,n-1);
for (i = 1;i <= n;i++)
{
if ( (s / tmp) % (i * i) != 0)
t = 0;
tmp = tmp / 10;
}
if (t)
count++;
}
printf ("%d\n",count);
getch();
}

我运行过你的程序,7、8、9的时候需要好长时间。
我也写了一个,学习学习。。。见笑了
在9的时候需要6.883ms。8需要0.867ms左右
#include <math.h>
#include <stdio.h>
main()
{
long n=0,i=0,s=0,count=0,j=0,temp=0;
scanf("%ld",&n);
i=(pow(10,n-1)/(n*n));

for(;;i++)
{
s=n*n*i;
if(s>=(int)(pow(10,n)))
break;
if(s<pow(10,n-1))
continue;
for(j=n,temp=s;j>1;j--)
{
if(temp%(j*j)!=0)
break;
temp /= 10;
}

if(j==1)
count++;
}
printf("%ld\n",count);
}

大于5位的时候会错误,因为你使用的TURBO C等16位的平台,int的最大数是32767,所以无法表示所有的5位数,你应该把变量定义为long,也就是下面一行:
int s,n,i,count = 0,t,tmp;

修改为:
long s,n,i,count = 0,t,tmp;

所有scanf和printf里面的%d都修改为%ld