【问题标题】:Getting odd results when trying to solve Collatz p‌r‌o‌b‌l‌e‌m尝试解决 Collat​​z p‌r‌o‌b‌l‌l‌m 时得到奇怪的结果
【发布时间】:2012-08-18 18:37:57
【问题描述】:

我正在尝试解决 Project Euler Problem 14。它要求找到生成最长序列的 100 万以下的数字。我所做的是创建一个向量 v,并使用特定数字的序列长度填充其元素。因此,位于位置 13 的元素将对应于由数字 13 生成的序列的长度,依此类推。但是,一些看似随机的元素需要非常大的数字,我无法弄清楚代码有什么问题。此外,当我用 1,000,000 对其进行测试时,我得到了一个完全错误的答案,但我知道该程序在手动测试并验证后可以处理一些小数字。

#include <iostream>
#include <vector>
using namespace std;

void find_longest(int n)
{
    int count = 1;
    int max = 0;
    int position;

    vector<int> v;
    v.push_back(0);
    v.push_back(0);

    for(int i = 1; i < n; i++)
    {
        long long int trainer = i;
        count = 1;
        while(trainer != 1)
        {
            if(trainer%2 == 0)
            {
                trainer /= 2;
                count++;
            }
            else
            {
                trainer = 3*trainer + 1;
                count++;
            }
        }
        v.push_back(count);
    }

    vector<int>::iterator it;

    for(it = v.begin(); it < v.end(); it++)
    {
        cout << v[*it] << endl;
        //if(v[*it] > max)
        //{
        //    max = v[*it];
        //    position = *it;
        //}
    }

    //cout << "The longest sequence is " << max << " terms long and is ";
    //cout << "generated by the number " << position << "." << endl;
}

int main()
{
    find_longest(100);
    //find_longest(1000000);
}

【问题讨论】:

  • 我没有看到您存储总最大总数的位置。我在代码顶部看到“max”,但如果“count”>“max”,我从未看到“count”覆盖“max”。
  • *it 不是号码吗?不是v[*it]
  • 另外,我很困惑你为什么要在向量中存储任何东西。我相信你应该只为创建最长序列的起始数字存储“max”和“value”。
  • 不,operator[] 的参数是索引,而不是迭代器。您需要的是max = *it,而position 将是v.begin() 和当前迭代器之间的距离,例如position = std::distance(v.begin(), it); v[*it] 所做的是用迭代器引用的值对向量进行索引。这是错误的逻辑。
  • 不客气。哦,标准库中有一个简洁的算法可以找到一个范围内的最大值:max = std::max_element(v.begin(), v.end()); 它在 &lt;algorithm&gt; 标头中。

标签: c++ collatz


【解决方案1】:

//删除类型不匹配的更改

您不需要记住向量中的所有 N 个数字。 您只需要当前序列长度。然后你计算下一个数字的序列长度,如果它比你已经拥有的大,你只保留最大的一个。

【讨论】:

  • 不,即使在 64 位操作系统中也不够。 sizeof(int) 始终为 32 位。在 LLP64 和 LP64 中,int 都定义为 32 位。
  • @artapet 并非所有的 int 都是 32 位的。 stackoverflow.com/questions/589575/size-of-int-long-etc
  • 另外,我不明白为什么 1,000,000 不适合 2^31 : 2,147,483,648?
  • 对不起,我错了,32位就够了。
猜你喜欢
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2020-10-08
  • 1970-01-01
相关资源
最近更新 更多