找出一个数字的除数

时间:2013-10-06 10:42:44

标签: c++ optimization sieve-of-eratosthenes number-theory

找出一个数的除数的最优化方法是什么,使得除数至少包含数字3?

e.g。 21 = 1,3,7,21

因此,只有一个除数的数字为3。

e.g。 62 = 1,2,31,62

因此,只有一个除数的数字为3,即31

编辑 - 我意识到这样做的最好方法是找出一个数字的所有因素,并检查包含数字3的因素。

找出因素的最佳方法:

Getting Factors of a Number

What is the best way to get all the divisors of a number?

1 个答案:

答案 0 :(得分:0)

这是我的一个扩展。它首先检查列表div3中是否存在可能的因子。如果没有,它会将候选人添加到 number / 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;
}
相关问题