# C++ Program to find out the distinct elements in a given sequence

C++Server Side ProgrammingProgramming

Suppose we are given three integer numbers n, x, y, and z. We have to make a sequence from the given integers where the first item of the sequence is (x modulo 231). Other than the first element, other elements in the sequence ai = (a(i-1) * y + z) modulo 231 , where 1 ≤ i ≤ n - 1. We have to find out the number of distinct integers in the sequence we made.

So, if the input is like n = 5, x = 1, y = 2, z = 1, then the output will be 5.

The unique values are {1, 3, 7, 15, 31}. So, the answer is 5.

To solve this, we will follow these steps −

• MOD := 2^31
• Define an array temp
• resize the array temp to the value of MOD
• p := x mod MOD
• temp[p] := true
• ans := 1
• for initialize i := 1, when i < n, update (increase i by 1), do −
• p := ((p * y) + z) mod MOD
• if temp[p] is true, then −
• Come out from the loop
• increase ans by 1
• temp[p] := true
• return ans

## Example

Let us see the following implementation to get better understanding −

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

const long long MOD = 2147483648;

int solve(int n, long long x, long long y, long long z) {
vector<bool> temp;
temp.resize(MOD);
long long p = x % MOD;
temp[p] = true;
int ans = 1;
for (int i = 1; i < n; ++i) {
p = ((p * y) + z) % MOD;
if (temp[p])
break;
++ans;
temp[p] = true;
}
return ans;
}

int main() {
cout<< solve(5, 1, 2, 1) <<endl;
return 0;
}

## Input

5, 1, 2, 1

## Output

5