zoukankan      html  css  js  c++  java
  • 湘大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;
    }
  • 相关阅读:
    memcached源码剖析5:并发模型
    memcached源码剖析4:并发模型
    深入剖析php执行原理(4):函数的调用
    深入剖析php执行原理(2):函数的编译
    剖析php脚本的超时机制
    strerror的坑
    深入理解php中的ini配置(2)
    深入理解php中的ini配置(1)
    一个“日期”字符串进行比较的case
    用valgrind检测php扩展内存泄露
  • 原文地址:https://www.cnblogs.com/yejianfei/p/2624248.html
Copyright © 2011-2022 走看看