首页 > 代码库 > 给定n,a求最大的k,使n!可以被a^k整除但不能被a^(k+1)整除。

给定n,a求最大的k,使n!可以被a^k整除但不能被a^(k+1)整除。

题目描述:

给定n,a求最大的k,使n!可以被a^k整除但不能被a^(k+1)整除。

输入:

两个整数n(2<=n<=1000),a(2<=a<=1000)

输出:

一个整数.

样例输入:
6 10
样例输出:
1

这个题首先如果数字小的话是可以考虑轮流试的,但是1000的数字范围无论是对阶乘还是幂都太大了。于是我们想一下,既然要求整除,说明每个素因子都是可以抵消的,这样我们就可以求解了。但是还要考虑到,因为后面是求哪个k,所以说我们不是对n!和a的幂分别求出对应的素数因子数组。我采取的方法是这样的:

1、分解得到n!的素数数组。

2、求出a的素数数组

3、求两者的商去最小值

 1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 using namespace std; 5 int su[168] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997}; 6 int main() 7 { 8     int n,a; 9     while(cin>>n>>a){10         int an[168];11         for(int i=0;i<168;i++){12             an[i]=0;13         }14         //fenjie n!15         for(int i=n;i>=0;i--){16             int index=0;17             int tmp=i;18             while(tmp>=2){19                 if(tmp%su[index]==0){20                     tmp/=su[index];21                     an[index]++;22                 }23                 else{24                     index++;25                 }26             }27         }28         int bn[168];29         for(int i=0;i<168;i++){30             bn[i]=0;31         }32         //fenjie a33         int t=a;34         int index=0;35         while(t>=2){36             if(t%su[index]==0){37                 t/=su[index];38                 bn[index]++;39             }40             else{41                 index++;42             }43         }44         double minn=100000;45         for(int i=0;i<168;i++){46             if(bn[i]!=0){47                 double f=an[i]/bn[i];48                 if(f<minn){49                     minn=f;50                 }51             }52         }53         cout<<int(minn+0.5)<<endl;54     }55     return 0;56 }