偶数个3

题目描述
在所有的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;
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cchoop

有用的话请杯肥宅水

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值