题目描述
在所有的N位数中,有多少个数中有偶数个数字3?
输入
第一行为一个整数T,代表有T组数据。(T<10000)
接下来T行,每行一个正整数N。(1<=N<=1000)
输出
每行输出一个整数,即方案数(由于结果可能很大,你只需要输出这个答案mod 12345的值。)。
样例输入
3
1
2
3
样例输出
8
73
674
错误解法:遍历每一个数,计算3的个数,得出n位数的结果,这种暴力解法对于低位数(int范围内)还有效,一旦数据位数太高,此方法完全不行。
代码:
using System;
namespace cchoop
{
class Program
{
public static void Main()
{
int n = 3;
int low = (int)Math.Pow(10, n - 1);
int high = low * 10 - 1;
int count = 0;
for (int i = low; i <= high; i++)
{
int tempNum = i;
int sanCount = 0;
while (tempNum > 0)
{
if (tempNum % 10 == 3)
{
sanCount++;
}
tempNum /= 10;
}
if (sanCount % 2 == 0)
{
count++;
}
}
Console.WriteLine(count);
}
}
}
正解
C语言实现:
int main()
{
int t;
int f[1010][2];
f[1][0]=8;
f[1][1]=1;
scanf("%d", &t);
while (t--){
int n;
scanf("%d", &n);
for(int i=2; i<=n; i++) {
f[i][0]=(f[i-1][0]*9+f[i-1][1])%12345;
f[i][1]=(f[i-1][0]+f[i-1][1]*9)%12345;
}
printf("%d\n",f[n][0]);
}
return 0;
}
c#递归实现:
using System;
namespace cchoop
{
class Program
{
public static void Main()
{
//8 8 1 1 9*0
//73 8*9+1 2*8+1 2 9*10
//674 73*9+17 3*73+17 3 9*100
Console.WriteLine(GetOuSan(1));
Console.WriteLine(GetOuSan(2));
Console.WriteLine(GetOuSan(30));
Console.WriteLine(GetOuSan(2));
}
//n代表位数
static int GetJiSan(int n)
{
if (n == 1)
{
return 1;
}
return (n * GetOuSan(n - 1) + GetJiSan(n - 1)) % 12345;
}
static int GetOuSan(int n)
{
if (n == 1)
{
return 8;
}
return (9 * GetOuSan(n - 1) + GetJiSan(n - 1)) % 12345;
}
}
}