诺伊曼的随机发生器 [英] Neumann's Random Generator

查看:113
本文介绍了诺伊曼的随机发生器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请先阅读任务: http://codeabbey.com / index / task_view / neumanns-random-generator

我必须跟踪迭代次数,但结果非常奇怪。在任务之后的示例中,我们有数字0001和4100,它们应该在2次和4次迭代后循环。但是我的结果是1,4或者如果我改变计数器2或5的位置但是从不改变2和4.这是我的代码:

I have to keep track of the number of iterations, but I get very strange results. In the example after the task we have the numbers 0001 and 4100 and they should come to loop after 2 and 4 iterations. But my results are 1, 4 or if I change the place of the counter 2 or 5 but never 2 and 4. Here is my code:

#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int n;
    int value;
    int counter;
    int result;
    int setvalue = 1; // use to exit the loop if setvalue == 0;
    cin >> n;
    vector<int> new_results(0); // use to store all the results from iterations
    vector<int> results_vec(0); // use to store the number of iterations for each number

    for (int i = 0; i < n ; i++)
    {

        cin >> value;
        while(setvalue == 1)
        {
            value = value*value;

            value = (value % 1000000) / 100;

            if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
            {
                results_vec.push_back(value);
            }
            else
            {
                counter = results_vec.size();
                new_results.push_back(counter);
                setvalue = 0;
            }

        }
        results_vec.clear();


    }
    for (int i = 0; i < new_results.size() ; i++)
    {
        cout << new_results[i] << " ";
    }

}


推荐答案

以你的方式进出一个字符串非常丑陋且计算上非常昂贵。

Going in and out of a string the way you have is really very ugly and extremely expensive computationally.

使用

(值%1000000)/ 100;

而不是提取中间的四位数字。这通过(1)取模数去除前两位数然后(2)用整数除法去除最后两位数。

instead to extract the middle four digits. This works by (1) taking the modulus to remove the leading two digits then (2) removing the last two with integer division.

因为它简单得多,我怀疑这也将修复你的错误。

As it's so much simpler, I suspect that will fix your bugs too.

这篇关于诺伊曼的随机发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆