分解质因子
// 分解质因子
// 2007-07-23
// By rappizit@yahoo.com.cn

#include <iostream>
#include <math.h>
using namespace std;

bool PrimeFactor (long long n)
{
int i, j;
bool first_factor = true;

if (n < 2)
{
cout << n << " = " << n << endl;
return false;
}
cout << n << " = ";
i = 2;
while (i <= (int) (sqrt ((double) (n))))
{
j = 0;
while (n % i == 0)
{
n /= i; // 将 n 里面的 i 因子除尽,确保下一个 i 是素数才能整除 n
j ++;
}
if (j) {
if (! first_factor)
{
cout << " * ";
} else {
first_factor = false;
}
cout << i;
if (j > 1)
{
cout << " ^ " << j;
}
}
i ++;
}
if (n != 1)
{
if (! first_factor)
{
cout << " * ";
}
cout << n;
}
cout << endl;
return (! first_factor); // 如果 n 是合数就返回 true
}

void main ()
{
long long n = 1;
while (n)
{
cin >> n;
if (n)
{
PrimeFactor (n);
}
}
}
控制台的输入输出信息:
-4
-4 = -4
1
1 = 1
3
3 = 3
7
7 = 7
15
15 = 3 * 5
31
31 = 31
63
63 = 3 ^ 2 * 7
127
127 = 127
255
255 = 3 * 5 * 17
65535
65535 = 3 * 5 * 17 * 257
4294967295
4294967295 = 3 * 5 * 17 * 257 * 65537
9223372036854775807
9223372036854775807 = 9223372036854775807
0
(退出)
==================================
2007-08-16
修改了一下代码。。
// PrimeFactor 分解质因子
// PrintPrimeFactor 输出分解式,如 100 = 2 ^ 2 * 5 ^ 2

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

vector < pair <int, int> > PrimeFactor (int n)
{
vector < pair <int, int> > v;
if (n < 1)
{
return v;
}
if (n == 1)
{
v.push_back (pair <int, int> (1, 1));
}
int i = 2, root = int (sqrt (double (n)));
while (i <= root)
{
if (n % i == 0)
{
int j = 0;
do {
n /= i;
j ++;
} while (n % i == 0);
v.push_back (pair <int, int> (i, j));
root = int (sqrt (double (n)));
}
i ++;
}
if (n != 1)
{
v.push_back (pair <int, int> (n, 1));
}
return v;
}

void PrintPrimeFactor (int n)
{
cout << n << " = ";
if (n < 1)
{
cout << n << endl;
return;
}
int i, size;
vector < pair <int, int> > v = PrimeFactor (n);
size = v.size ();
for (i = 0; i < size - 1; i ++)
{
cout << v [i].first;
if (v [i].second > 1)
{
cout << " ^ " << v [i].second;
}
cout << " * ";
}
cout << v [i].first;
if (v [i].second > 1)
{
cout << " ^ " << v [i].second;
}
cout << endl;
return;
}

void main ()
{
int n;
cin >> n;
PrintPrimeFactor (n);
return;
}



































































控制台的输入输出信息:
-4
-4 = -4
1
1 = 1
3
3 = 3
7
7 = 7
15
15 = 3 * 5
31
31 = 31
63
63 = 3 ^ 2 * 7
127
127 = 127
255
255 = 3 * 5 * 17
65535
65535 = 3 * 5 * 17 * 257
4294967295
4294967295 = 3 * 5 * 17 * 257 * 65537
9223372036854775807
9223372036854775807 = 9223372036854775807
0
(退出)
==================================
2007-08-16
修改了一下代码。。












































































