定义:给出一个正整数,将其携程几个素数的乘积,这个过程称为整数分解。
例题:HDU_1164 https://vjudge.net/problem/HDU-1164
一、试除法
算法:令m = n,从2~sqrt(N) 一一枚举,如果当前数能够整除m,那么当前数就是n的素因子,并用整数m将当前数除尽为止。若循环结束后m是大于1的整数,那么此时的m也是n的素因子。
代码:
#include <bits/stdc++.h>
using namespace std;
int Factor[100], Cnt;
void Divide(int N)
{
Cnt = 0;
for(int i = 2; i <= sqrt((double)N); i++)
{
while(N%i == 0)
{
Factor[Cnt++] = i;
N/=i;
}
}
if(N!=1)
Factor[Cnt++] = N;
}
int main()
{
int N;
while(~scanf("%d", &N))
{
Divide(N);
for(int i = 0; i < Cnt-1; i++)
cout << Factor[i] <<"*";
cout << Factor[Cnt-1] << endl;
}
}
二、筛选法对整数分解
算法:因为试除法进行了很多不必要的试除运算,如果首先将2~sqrt(n) 的所有素数打表,然后对应素数表一一试除将会大大节省时间。
代码:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 65536;
int Factor[100], Cnt;
int Prime[MAXN], nPrime;
bool isPrime[MAXN];
void getPrime()
{
memset(isPrime, 1, sizeof(isPrime));
isPrime[0] = isPrime[1] = 0;
nPrime = 0;
for(int i = 2; i*i <= MAXN; i++)
{
if(isPrime[i])
{
Prime[nPrime++] = i;
for(int j = i+i; j < MAXN; j+=i)
{
isPrime[j] = 0;
}
}
}
}
void Divide(int n)
{
Cnt = 0;
for(int i = 0; i < nPrime; i++)
{
if(Prime[i] > n) break;
while(n%Prime[i] == 0)
{
Factor[Cnt++] = Prime[i];
n/=Prime[i];
}
}
if(n!=1)
{
Factor[Cnt++] = n;
}
}
int main()
{
int D;
getPrime();
while(~scanf("%d", &D))
{
Divide(D);
for(int i = 0; i < Cnt-1; i++)
cout << Factor[i] <<"*";
cout << Factor[Cnt-1] << endl;
}
}