TOJ-1304 Factovisors
The factorial function, n! is defined thus for n a non-negative integer:
0! = 1 n! = n * (n-1)! (n > 0)We say that a divides b if there exists an integer k such that
k*a = bThe input to your program consists of several lines, each containing two non-negative integers, n and m, both less than 231. For each input line, output a line stating whether or not m divides n!, in the format shown below.
Sample Input
6 9 6 27 20 10000 20 100000 1000 1009
Sample Output
9 divides 6! 27 does not divide 6! 10000 divides 20! 100000 does not divide 20! 1009 does not divide 1000!
Source: Waterloo Local Contest Jan. 31, 1999
因式分解m,看n!能否分解出这些因式。
#include <stdio.h> #include <memory.h> struct factor{ int p; int n; }; int prime[6000]; //PI(50000)<6000 bool flag[50000];// 50000^2 > 2^31 factor f[500]; void getprime() { int s = 0; memset(flag,false,sizeof(flag)); for(int i=2;i<50000;i++) { if(!flag[i]) { prime[s++] = i; for(unsigned int j=i*i;j<50000;j=j+i) flag[j] = true; } } } void getfactor(int m,int &g){ g = 0; for(int i=0;prime[i]*prime[i]<=m;i++) { if(m%prime[i]==0) { f[g].p = prime[i]; f[g].n++; m = m / prime[i]; while(m%prime[i]==0) { f[g].n++; m = m / prime[i]; } g++; } if(m == 1) break; } if(m>1)//m是大于50000的素数 { f[g].p=m; f[g].n++; g++; } } bool isdivided(int n,int m,int g){ int pnum,t; for(int i=g-1;i>=0;i--){ pnum = 0; t = f[i].p; while(n>=t){ pnum = pnum + n / t; t = t * f[i].p; } if(pnum < f[i].n) return false; } return true; } int main() { int n,m,i,g; getprime(); while(scanf("%d%d",&n,&m)!=EOF) { for(i=0;i<1000;i++){ f[i].n=0;//因子初始化 } if(n<=1 && m>1) { printf("%d does not divide %d!\n",m,n); continue; } if(m==0) { printf("%d does not divide %d!\n",m,n); continue; } if(n>=m) { printf("%d divides %d!\n",m,n); continue; } getfactor(m,g); if(isdivided(n,m,g)) printf("%d divides %d!\n",m,n); else printf("%d does not divide %d!\n",m,n); } return 0; }
ps:开始写了个t = t * t,导致一直报错Runtime Error SIGFPE。