题解 SP4942 【FACT0 - Integer Factorization (15 digits)】
给一个map做法与普通做法
分解质因数其实并不难,可以每次边统计边输出,也可以用map,将i当为key值,cnt为值,最后输出。
两种代码:
1、map
#include <iostream>
#include <map>
using namespace std;
#define fast_io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
map<long long, long long> mp;
int main()
{
fast_io;
long long n;
while(cin >> n && n)
{
mp.clear();
long long tmp = n;
for(register long long i = 2; i * i <= tmp; i++)
{
long long cnt = 0;
if(n % i == 0)
{
while(n % i == 0)
{
cnt++;
n /= i;
}
mp[i] = cnt;
}
}
if(n != 1)
{
mp[n] = 1;
}
map<long long, long long>::iterator endd = mp.end();
for(register map<long long, long long>::iterator it = mp.begin(); it != endd; ++it)
{
cout << it -> first << "^" << it -> second << " ";
}
cout << endl;
}
return 0;
}
2、普通
#include <iostream>
using namespace std;
#define fast_io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
int main()
{
fast_io;
long long n;
while(cin >> n && n)
{
long long tmp = n;
for(register long long i = 2; i * i <= tmp; i++)
{
long long cnt = 0;
if(n % i == 0)
{
while(n % i == 0)
{
cnt++;
n /= i;
}
cout << i << "^" << cnt << " ";
}
}
if(n != 1)
{
cout << n << "^1";
}
cout << endl;
}
return 0;
}

浙公网安备 33010602011771号