分解质因数:
vector<int> factors(int n)
{
int r = n;
vector<int> factors; int count = 0; int nextf = 2;
for (int i = nextf; i <= r; i++)
{
if (r % i) continue;
factors.push_back(i); count++; nextf = i+1; while (r % i == 0) r /= i;
}
cout << n << " = ";
bool first = true;
for (int j = 0; j < count; j++)
{
int f = factors[j];
while (n % f == 0)
{
if (first) { cout << f; first = false; }
else cout << " * " << f;
n /= f;
}
}
cout << endl;
return factors;
}
最大公因数
int greatest_common_factor(int n1, int n2)
{
if (n1 == n2) return n1;
int small = n1, big = n2; if (n2 < n1)
{
small = n2; big = n1;
}
for (int j = small; j >= 2; j--)
{
if (n2 % j == 0 && n1 % j == 0) return j;
}
return 1;
}
最小公倍数
int lease_common_multiple(int n1, int n2)
{
int cf = greatest_common_factor(n1, n2); return n1 * n2 / cf;
}