这两道题就不给出题目,两道题十分类似,都是关于伪随机数。
只不过第一题初始数字从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;
}
}
}