Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C++ Program to find out the distinct elements in a given sequence
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
- p := ((p * y) + z) mod MOD
- if temp[p] is true, then −
- Come out from the loop
- increase ans by 1
- temp[p] := true
Example
Let us see the following implementation to get better understanding −
#include#include #include #include #include using namespace std; const long long MOD = 2147483648; int solve(int n, long long x, long long y, long long z) { vector temp; temp.resize(MOD); long long p = x % MOD; temp[p] = true; int ans = 1; for (int i = 1; i Input
5, 1, 2, 1Output
5
Advertisements
