描述
小乐乐从老师口中听到了二段数这个名词,想更深入的了解二段数。
二段数是这样的正整数:恰好包含两种不同的十进制数字s和t,s不是0,并且s的所有出现均排列在所有的t的前面。例如,44444411是二段数(s是4,t是1),41、10000000和5555556也是。但4444114和44444都不是二段数。
这时老师问小乐乐:给你一个任意的正整数n,你能求出比n大并且是n的倍数的最小二段数吗?请你帮助小乐乐解答这个问题。
输入描述:
多组输入,每组输入包含一个正整数n (1 ≤ n ≤ 99999)
题目保证测试数据总数不超过500组,当输入n=0时程序结束。
输出描述:
对于每组测试用例,输出正整数n,后面紧跟“: ”,输出答案并换行,即比n大且是n的倍数的最小二段数。
#include <stdio.h>
const int maxn=10010;
int a[maxn],b[maxn];
int m,total,s,t,aptotal,apm,aps,apt,k;
int n;
int ck()
{
int p,r;
if (total > 5)
return 1;
p=s;
r=t;
for(int q=0;q<m;q++)
{
p=p*10+s;
}
for (int q = 0; q < total-m; q++)
p = p * 10;
for (int q = 1; q < total-m; q++)
r = r * 10 + t;
return p+r>n;
}
int main()
{
while(scanf("%d", &n) , n)
{
printf("%d: ", n);
if (n == 1) {
printf("10");
continue;
}
a[0]=1;
b[0]=1;
for(int i=1;i<9999;i++)
a[i]=(a[i-1]*10+1)%n;
for (int i = 1; i < 999; i++)
b[i] = b[i-1]*10%n;
for (total = 1, aps = 0; total < 9999; total++) {
k = 0;
if ((n % 10 == 0 || n % 25 == 0) && total> 11)
k = total - 11;
for (m = k; m < total; m++)
for (s = 1; s < 10; s++)
for (t = 0; t < (n % 10 ? 10 : 1); t++)
if(t!=s&&(((long long)a[m]) * b[total - m] * s + a[total - m - 1] * t) % n == 0 && ck()&&
(!aps||s<aps))
{
aptotal=total;
apm=m;
aps=s;
apt=t;
}
if (aps)
break;
}
for (int x = 0; x < apm + 1; x++)
printf("%d",aps);
for (int x = 0; x < aptotal - apm; x++)
printf("%d",apt);
printf("\n");
}
return 0;
}
解题思路
例如999999993 就可以看做个8个9 1个3
对应四个变量 我们存储一下m个s和n个t组成
二段数m,s,n,t除以N的余数等于(a[m]b[n]s+a[n]*t) mod N。
上述代码主要有两个难点:
1.a[],b[]两个数组为啥这样赋值
2.为啥二段数m,s,n,t除以N的余数等于(a[m]b[n]s+a[n]*t) mod N
其实主要是求模运算具有可乘性和可加性
什么是可加性
24%10=4 等价于 (20+4)%10=(20%10+4%10)%10
436%10=6 等价于 (400+36)%10=(400%10+36%10)%10
什么是可乘性
24%10=4 等价于 (2x12)%10=( (2%10) x (12%10) )%10
436%10=6 等价于 (4x109)%10=( (4%10) x (36%10) )%10
而上面的代码就是通过模运算的这两个性质,优化算法的
例如:
//m=9,s=9,n=1,t=3,输入的数为2019
//a[]={0,1%2019,11%2019,111%2019,1111%2019.....}
//b[]={1%2019,10%2019,100%2019,1000%2019.....}
9999999993%2019
=(9x111111111x10+3x1)%2019
=( (9x111111111x10) % 2019 + (3x1) % 2019 ) % 2019
=( (9%2019) x (111111111%2019) x (10%2019) + (3%2019) x (1%2019) ) % 2019
=( 9x(111111111%2019)x(10%2019)+ 3x(1%2019) )%2019
=(s*a[m]*b[n]+t*a[n])%2019
如此上诉两个问题就很容易理解了
结论:学好数学真的很重要啊!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!