Files
freeCodeCamp/curriculum/challenges/ukrainian/10-coding-interview-prep/rosetta-code/linear-congruential-generator.md
2022-10-18 12:59:49 +05:30

3.2 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5e4ce2f5ac708cc68c1df261 Лінійний конгруентний метод 1 385266 linear-congruential-generator

--description--

A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized numbers calculated with a discontinuous piecewise linear equation. Усі лінійні конгруентні генератори працюють за формулою:

r_{n + 1} = (a \times r_n + c) \bmod m

Де:

  • $ r_0 $ — початкове число.
  • $r_1$, $r_2$, $r_3$, ..., — випадкові числа.
  • $a$, $c$, $m$ — константи.

Якщо уважно вибирати значення a, c і m, то генератор створює рівномірний розподіл цілих чисел від 0 до m - 1.

LCG numbers have poor quality. r_n та r\_{n + 1} не є незалежними, як справжні випадкові числа. Anyone who knows r_n can predict r\_{n + 1}, therefore LCG is not cryptographically secure. The LCG is still good enough for simple tasks like Miller-Rabin primality test, or FreeCell deals. Among the benefits of the LCG, one can easily reproduce a sequence of numbers, from the same r_0. Можна також відтворити таку послідовність за допомогою іншої мови програмування, оскільки формула дуже проста.

--instructions--

Напишіть функцію з параметрами r_0,a,c,m,n, яка видає r_n.

--hints--

linearCongGenerator має бути функцією.

assert(typeof linearCongGenerator == 'function');

linearCongGenerator(324, 1145, 177, 2148, 3) має повернути число.

assert(typeof linearCongGenerator(324, 1145, 177, 2148, 3) == 'number');

linearCongGenerator(324, 1145, 177, 2148, 3) має повернути 855.

assert.equal(linearCongGenerator(324, 1145, 177, 2148, 3), 855);

linearCongGenerator(234, 11245, 145, 83648, 4) має повернути 1110.

assert.equal(linearCongGenerator(234, 11245, 145, 83648, 4), 1110);

linearCongGenerator(85, 11, 1234, 214748, 5) має повернути 62217.

assert.equal(linearCongGenerator(85, 11, 1234, 214748, 5), 62217);

linearCongGenerator(0, 1103515245, 12345, 2147483648, 1) має повернути 12345.

assert.equal(linearCongGenerator(0, 1103515245, 12345, 2147483648, 1), 12345);

linearCongGenerator(0, 1103515245, 12345, 2147483648, 2) має повернути 1406932606.

assert.equal(
  linearCongGenerator(0, 1103515245, 12345, 2147483648, 2),
  1406932606
);

--seed--

--seed-contents--

function linearCongGenerator(r0, a, c, m, n) {

}

--solutions--

function linearCongGenerator(r0, a, c, m, n) {
    for (let i = 0; i < n; i++) {
        r0 = (a * r0 + c) % m;
    }
    return r0;
}