【发布时间】:2017-04-13 01:22:58
【问题描述】:
要找到数的因数,我使用函数void primeFactors(int n)
# include <stdio.h>
# include <math.h>
# include <iostream>
# include <map>
using namespace std;
// A function to print all prime factors of a given number n
map<int,int> m;
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n%2 == 0)
{
printf("%d ", 2);
m[2] += 1;
n = n/2;
}
// n must be odd at this point. So we can skip one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i+2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
int k = i;
printf("%d ", i);
m[k] += 1;
n = n/i;
}
}
// This condition is to handle the case whien n is a prime number
// greater than 2
if (n > 2)
m[n] += 1;
printf ("%d ", n);
cout << endl;
}
/* Driver program to test above function */
int main()
{
int n = 72;
primeFactors(n);
map<int,int>::iterator it;
int to = 1;
for(it = m.begin(); it != m.end(); ++it){
cout << it->first << " appeared " << it->second << " times "<< endl;
to *= (it->second+1);
}
cout << to << " total facts" << endl;
return 0;
}
你可以在这里查看。 Test case n = 72。
http://ideone.com/kaabO0
如何使用上述算法解决上述问题。 (可以进一步优化吗?)。我也必须考虑大数字。
我想做什么..
以 N = 864 为例,我们发现 X = 72 为 (72 * 12 (因子数)) = 864)
【问题讨论】:
-
您能举例说明您正在寻找什么吗?例如,如果
x = 12,那么唯一因子的数量是6(1、2、3、4、6、12)和n = 12 * 6 = 72?或者你想计算素数(2 * 2 * 3),在这种情况下n = 12 * 3 = 36? -
大数是什么意思?你能说出N的范围吗?
-
Why is “using namespace std” considered bad practice?。你应该包括
<cstdio>and<cmath>而不是stdio.h和math.h
标签: c++ algorithm optimization factors