PKU 1730

Perfect Pth Powers

Type:挺BT的数学题

解法:X = 2p1×3p2×5p3....(2,3,5...为素因子),求p1,p2,p3...的最大公约数

Key:由于题目说是"have magnitude(值) at least 2", "(32-bit)", 所以需要用64位整数,并且要考虑负数的情况,很多人都卡在这上面(是题目叙述不清,还是英文差?)。

代码
   
     
#include < stdio.h >
#include
< string .h >
#define NL 150000

bool p0[NL];
int pnum[NL / 9 ], np;

void prim()
{
__int64 i, j;
memset(p0,
0 , sizeof (p0));
for (i = 2 ; i < NL / 2 ; i ++ ) {
if ( ! p0[i]) {
j
= i * i;
while (j < NL) {
p0[j]
= 1 ;
j
+= i;
}
}
}
np
= 0 ;
for (i = 2 ; i < NL; i ++ ) {
if ( ! p0[i]) pnum[np ++ ] = ( int )i;
}
}

int gcd( int a, int b)
{
while (b) {
int t = a;
a
= b;
b
= t % b;
}
return a;
}

int main()
{
prim();
int cnt[ 1000 ];
__int64 y;
while (scanf( " %I64d " , & y) != EOF ){
if ( ! y) break ;
int i = 0 ;
bool suc = false , pos = false ;
int fact, c = 0 ;
if (y < 0 ) { y = - y; pos = true ; }
__int64 t
= pnum[i];
while (t * t <= y) {
if (y % pnum[i] == 0 ) {
suc
= true ;
fact
= pnum[i];
cnt[c]
= 0 ;
while (y > 1 && y % fact == 0 ) {
y
/= fact;
cnt[c]
++ ;
}
c
++ ;
if (y == 1 ) {
break ;
}
}
i
++ ;
t
= pnum[i];
}
int gc = cnt[ 0 ];
for (i = 1 ; i < c; i ++ )
gc
= gcd(gc, cnt[i]);
if (suc) {
if ( ! pos) printf( " %d\n " , gc);
else {
while (gc > 1 && ! (gc & 1 )) gc /= 2 ;
printf(
" %d\n " , gc);
}
}
else printf( " 1\n " );
}
return 0 ;
}

 

你可能感兴趣的:(pku)