想到分解质因数的话就很简单了,注意此题要求幂次至少为1,所以幂次为0即为Impossible to divide。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <map> 5 using namespace std; 6 7 const int N = 10000; 8 bool visit[N]; 9 int prime[N]; 10 int n, m, ans, pn; 11 12 void sieve() 13 { 14 memset( visit, 0, sizeof(visit) ); 15 visit[0] = visit[1] = 1; 16 pn = 0; 17 for ( int i = 0; i < N; i++ ) 18 { 19 if ( !visit[i] ) 20 { 21 prime[pn++] = i; 22 for ( int j = i + i; j < N; j += i ) 23 { 24 visit[j] = 1; 25 } 26 } 27 } 28 } 29 30 int work( int num, int p ) 31 { 32 int res = 0; 33 while ( num ) 34 { 35 res += num / p; 36 num /= p; 37 } 38 return res; 39 } 40 41 void solve() 42 { 43 map<int, int> mp; 44 int r = n; 45 for ( int i = 0; prime[i] * prime[i] <= r; i++ ) 46 { 47 if ( r % prime[i] == 0 ) 48 { 49 while ( r % prime[i] == 0 ) 50 { 51 mp[prime[i]]++; 52 r = r / prime[i]; 53 } 54 } 55 } 56 if ( r > 1 ) 57 { 58 mp[r]++; 59 } 60 map<int, int>::iterator it; 61 int ans = 9999999; 62 for ( it = mp.begin(); it != mp.end(); it++ ) 63 { 64 int fir = (*it).first, sec = (*it).second; 65 int cnt = work( m, fir ); 66 ans = min( ans, cnt / sec ); 67 } 68 if ( !ans ) 69 { 70 puts("Impossible to divide"); 71 } 72 else 73 { 74 printf("%d ", ans); 75 } 76 } 77 78 int main () 79 { 80 sieve(); 81 int t; 82 scanf("%d", &t); 83 for ( int _case = 1; _case <= t; _case++ ) 84 { 85 printf("Case %d: ", _case); 86 scanf("%d%d", &n, &m); 87 solve(); 88 } 89 return 0; 90 }