[英]finding out the divisors of a number
找出一个数的除数,使除数至少包含数字3的最优化方法是什么?
例如21 = 1,3,7,21
因此,只有一个除数中有数字3。
例如62 = 1,2,31,62
因此,只有一个除数的数字为3,即31
EDIT-i意识到,执行此操作的最佳方法是找出一个数字的所有因子,并检查包含数字3的因子。
找出因素的最佳方法:
这是我的扩展。 首先检查列表div3
是否存在可能的因素。 如果不是,则将候选数最多增加为/ 2,跳过此列表可能已经考虑的值,因此将添加“ 37”和“ 43”,但不会添加“ 36”或“ 39”。
以上部分应视为“设置”。 如果知道输入约束(最大输入值),则可以计算一次向量div3
,然后将其存储在程序中。
如果列表div3
是最新的,则应将输入分解为这些数字之一。 如果不能,则所有因素均不包含“ 3”。 如果可以 ,则显示剩余部分,可以使用常规方法将其进一步分解。
我认为这是“优化的”,因为首先检查了约束“任何因素都应包含'3'”。 仅当找到任何有效因子时,才需要计算所有其他因子。
我的第一个程序使用的是<vector>
及其类似物,请谨慎对待:-)
(编辑)我现在注意到因子检查循环遍历整个div3
向量。 当然,只需要增加到number/2
。 留给读者练习。
(附加编辑) find3
在这里是反向迭代器。 出于某种原因,这似乎很合适,但是我不记得为什么会这样:)如果检查不超过number/2
,则需要将其更改为常规的正向迭代器。
#include <iostream>
#include <vector>
using namespace std;
int contains_3 (int value)
{
while (value && (value % 10) != 3)
value /= 10;
return value;
}
int main (int argc, char **argv)
{
int number, found_flag, last_div3, adjust, adjust_digit;
vector<int> div3;
vector<int>::reverse_iterator find3;
vector<int>::iterator it;
// a little seeding
div3.push_back(3);
div3.push_back(13);
div3.push_back(23);
if (argc != 2)
return -1;
number = atoi (argv[1]);
found_flag = 0;
// do we need to expand div3?
last_div3 = div3.back();
while (last_div3 * 2 < number)
{
// if this number contains a '3' in any other place than the last,
// simply increment it
if ((last_div3 % 10) != 9 && contains_3(last_div3/10))
{
last_div3++;
} else
{
// no? then simply pick the next multiple of 10 and add 3
last_div3 /= 10;
last_div3++;
last_div3 *= 10;
if (!contains_3(last_div3))
last_div3 += 3;
}
// check if it should be in the list
for (it = div3.begin() ; it != div3.end() && (last_div3 % *it); ++it) ;
if (it == div3.end())
{
div3.push_back(last_div3);
}
}
cout << "list is now: ";
for (it = div3.begin() ; it != div3.end(); ++it)
cout << ' ' << *it;
cout << endl;
for (find3 = div3.rbegin(); !found_flag && find3 != div3.rend(); find3++)
{
if (!(number % *find3))
{
cout << "candidate: " << *find3 << ", remaining to sieve: " << number/(*find3) << endl;
found_flag++;
}
}
if (!found_flag)
cout << "None found" << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.