【UvaOJ】【基础题目】【Maths - Number Theory】 408和350 伪随机数

这两道题就不给出题目,两道题十分类似,都是关于伪随机数。


只不过第一题初始数字从0开始,在得到mod个数字之前,若第二次出现0时,必然出现循环而无法产生所有数字,这时判定为bad。


而第二题有所不同,第二题提示了循环开始的数字不一定是第一个seed,所以要运用一个数组,依次存入产生的随机数,直到发现新待加入的元素在数组中已存在,那么则表示出现了循环,此时要用当前的数组大小减去该重复元素第一次出现的位置,才能得到循环的大小。


代码:


408:

#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<cmath>
#include<iomanip>
using namespace std;

int main()
{
	int s, m;
	while (cin >> s >> m)
	{
		int count = 1;
		int now = 0;
		while (true)
		{
			now = (now + s) % m;
			count++;
			if (now == 0 && count <= m)
			{
				cout << setiosflags(ios::right) << setw(10) << s << setw(10) << m << "    " << "Bad Choice" << endl<<endl;
				break;
			}
			if (count > m)
			{
				cout << setiosflags(ios::right) << setw(10) << s << setw(10) << m << "    " << "Good Choice" << endl<<endl;
				break;
			}
		}
	}
}



350:

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

int main()
{
	int z, i, m, l;
	int count = 0;
	while (cin >> z >> i >> m >> l)
	{
		if (z == 0 && i == 0 && l== 0 && m == 0)
			break;
		else
		{
			int result;
			count++;
			vector<int> all;
			int now = l;
			all.push_back(now);
			while (true)
			{
				now = ( now * z + i) % m;
				vector<int>::iterator it = find(all.begin(), all.end(), now);
				if (it == all.end())
					all.push_back(now);
				else
				{
					int pos;
					for (pos = 0 , it = all.begin(); it < all.end(); it++)
					{
						if (*it == now)
							break;
						else
							pos++;
					}
					result = all.size() - pos;
					break;
				}
			}
			cout << "Case " << count << ": " << result << endl;
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值