湘大OJ第1490题 Generating Random Numbers

  湘大OJ第1490题,Generating Random Numbers题目链接)。

Generating Random Numbers

Description

Anyone who considers arithmetical methods of producing random digits is,
of course, in a state of sin.
- John von Neumann

As a talented mathematician, von Neumann invented a method to generate random numbers sequentially. The method is quite simple: Given A, B, M, and the first element of the sequence x[0], then we will get \(\displaystyle x[i] = (x[i-1] * A + B) % M\), for all \(i > 0\).

As an even more talented mathematician, you found his method are problematic. The sequence is not really random, that is, it always repeated previous numbers after several steps. For example, assume A = 3, B = 5, M = 7, and x[0] = 2, then we will get x[1] = 4, x[2] = 3, x[3] = 0, x[4] = 5, x[5] = 6, x[6] = 2, x[7] = 4, x[8] =3, … We can see that x[6] is the same as x[0], then the same sequence begins to repeat again and again. Now you want to write a program to find that, for a given A,B,M and x[0], what is the smallest i so that x[i] equal to a previous number.

Input

The first line of the input contains an integer T (T ≤ 100), indicating the number of test cases. Then T cases follow. Each case contains one line with 4 numbers A, B, M and x[0]. You can assume 1 ≤ M ≤ 30000, 0 ≤ A, B, x[0] ≤ M.

Output

Output one line for each test case, indicating the smallest i that x[i] is repeated.

Sample Input

2
3 5 7 2
3 5 7 1

Sample Output

6
1

Source

“开启时代杯”湘潭市第二届大学生程序设计大赛 (Internet)

  这一题没什么难度,暴力枚举,直到相等。

  C语言代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef int COUNT;

int main (void)
{
    int n;
    int a, b, m, x0, x;
    COUNT i;
    scanf( "%d", &n );
    while ( n -- )
    {
        scanf( "%d%d%d%d", &a, &b, &m, &x0 );
        x = x0;
        for ( i = 1 ;  ; i ++ )
        {
            x = (x * a + b) % m;
            if ( x == x0 )
                break;
        }
        printf( "%d\n", i );
    }
    return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值