Prime Bases
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 802 Accepted Submission(s): 380
Problem Description
Given any integer base b >= 2, it is well known that every positive integer n can be uniquely represented in base b. That is, we can write
n = a0 + a1*b + a2*b*b + a3*b*b*b + ...
where the coefficients a0, a1, a2, a3, ... are between 0 and b-1 (inclusive).
What is less well known is that if p0, p1, p2, ... are the first primes (starting from 2, 3, 5, ...), every positive integer n can be represented uniquely in the "mixed" bases as:
n = a0 + a1*p0 + a2*p0*p1 + a3*p0*p1*p2 + ...
where each coefficient ai is between 0 and pi-1 (inclusive). Notice that, for example, a3 is between 0 and p3-1, even though p3 may not be needed explicitly to represent the integer n.
Given a positive integer n, you are asked to write n in the representation above. Do not use more primes than it is needed to represent n, and omit all terms in which the coefficient is 0.
Input
Each line of input consists of a single positive 32-bit signed integer. The end of input is indicated by a line containing the integer 0.
Output
For each integer, print the integer, followed by a space, an equal sign, and a space, followed by the mixed base representation of the integer in the format shown below. The terms should be separated by a space, a plus sign, and a space. The output for each integer should appear on its own line.
Sample Input
Sample Output
123 = 1 + 1*2 + 4*2*3*5
456 = 1*2*3 + 1*2*3*5 + 2*2*3*5*7
123456 = 1*2*3 + 6*2*3*5 + 4*2*3*5*7 + 1*2*3*5*7*11 + 4*2*3*5*7*11*13
先从大到小求出p1*p2*p3*....*pn ,再求出系数 。
比如n=123,先求出2*3*5,当再乘上7时 ,已经大于123了,所以最后一项的base是2*3*5,求系数的时候,再从1枚举到7-1 ,只有4是合适的,当枚举到5的时候,已经超出了123。。然后再分别依次求出其他项。
代码:
#include <stdio.h>
#include <string.h>
int prime[] = {2,3,5,7,11,13,17,19,23,29,31};
int c[20] ;
int p[20] ;
int f(int s , int base , int d)
{
for(int i = 1; i < d ; ++i)
{
if(i*base>s || i*base<0) //i*base<0是为了防止溢出,,下同
{
return i-1 ;
}
}
return 0 ;
}
int main()
{
int n ;
while(~scanf("%d",&n) && n)
{
int s = n , index = 0 ;
memset(c,0,sizeof(c)) ;
while(s)
{
int base = 1 , i = 0 ;
for( ; base*prime[i]<=s && base*prime[i] > 0 ; ++i)
{
base *= prime[i] ;
}
c[index] = f(s,base,prime[i+1]) ;
p[index] = i ;
s -= base*c[index] ;
++index ;
}
printf("%d = ",n) ;
for(int i = index-1 ; i >= 0 ; --i)
{
if(c[i] == 0) //系数等于0时跳过。
continue ;
printf("%d",c[i]);
for(int j = 0 ; j < p[i] ; ++j)
{
printf("*%d",prime[j]) ;
}
if(i!=0)
{
printf(" + ") ;
}
}
puts("") ;
}
return 0 ;
}
与君共勉