[英]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.