Prime Land
Description Everybody in the Prime Land is using a prime base number system. In this system, each positive integer x is represented as follows: Let {pi}i=0,1,2,... denote the increasing sequence of all prime numbers. We know that x > 1 can be represented in only one way in the form of product of powers of prime factors. This implies that there is an integer kx and uniquely determined integers ekx, ekx-1, ..., e1, e0, (ekx > 0), that Input The input consists of lines (at least one) each of which except the last contains prime base representation of just one positive integer greater than 2 and less or equal 32767. All numbers in the line are separated by one space. The last line contains number 0. Output The output contains one line for each but the last line of the input. If x is a positive integer contained in a line of the input, the line in the output will contain x - 1 in prime base representation. All numbers in the line are separated by one space. There is no line in the output corresponding to the last ``null'' line of the input. Sample Input Sample Output Source 算法分析: 题意: 输入是一行数字,并且数字是两两成对的,第一个表示的是质因子,第二个表示的是这个质因子的次数。通过这些可以得到一个确定的值为n,现在想让你计算(n-1)的质因子,按照输入的方式将其表示出来。 例如,5 1 2 1 n=5^1+2^1=7,求6的这种形式,6=3^2,底数必须是质因子,唯一分解定理之存在一组。 分析: 接受数据看一下,其他就简单了。 直接一个模拟过程就ok 代码实现 |
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
const long N = 36000;
int cnt[N];
long prime[N] = {0},num_prime = 0;
int isNotPrime[N] = {1, 1};
int Prime()
{
for(long i = 2 ; i < N ; i ++)
{
if(! isNotPrime[i])
prime[num_prime ++]=i;
//关键处1
for(long j = 0 ; j < num_prime && i * prime[j] < N ; j ++)
{
isNotPrime[i * prime[j]] = 1;
if( !(i % prime[j] ) ) //关键处2
break;
}
}
return 0;
}
int main()
{
Prime();
while(1)
{
long long ans=1;
long long p,e;
int flag=0;
while(1)
{
scanf("%lld",&p);
if(p==0) {flag=1; break;}
scanf("%lld",&e);
ans*=pow(p,e);
char c=getchar();
if(c=='\n') break;
}
if(flag==1) break;
ans--;
flag=0 ;
int pos;
memset(cnt,0,sizeof(cnt));
for(int i=2;i<=32767;i++)
{
if(ans==1) break;
if(isNotPrime[i]==0)
{
while(ans%i==0)
{
cnt[i]++;
ans/=i;
if(flag==0) //记录初始位置,为了下面的格式输出
{
flag=1;
pos=i;
}
}
}
}
for(int i=32767;i>=2;i--)
{
if(cnt[i]&&pos!=i)
{
printf("%d %d ",i,cnt[i]);
}
else if(cnt[i]&&pos==i) //不要多余的空格
{
printf("%d %d\n",i,cnt[i]);
break;
}
}
}
return 0;
}