Bit Array in C++ | HackerRank Solution

Hello there, today we are going to solve Bit Array Hacker Rank Solution in C++.

Hello there, today we are going to solve Bit Array Hacker Rank Solution in C++.

Bit Array in C++
Table Of Contents 👊

Problem

You are given four integers: N, S, P, Q. You will use them in order to create the sequence a with the following pseudo-code.

a[0] = S (modulo 2^31)
for i = 1 to N-1
    a[i] = a[i-1]*P+Q (modulo 2^31) 

Your task is to calculate the number of distinct integers in the sequence a.

Input Format

Four space separated integers on a single line, N, S, P, and Q respectively.

Output Format

A single integer that denotes the number of distinct integers in the sequence a.

Constraints

  • 1 <= N <= 10^8
  • 0 <= S, P, Q <= 2^31

Sample Input

3 1 1 1

Sample Output 

3

Explanation 

a = [1, 2, 3]

Hence, there are 3 different integers in the sequence.

Solution - Bit Array in C++

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


int main() {
    unsigned long long n,s,p,q,r=0,ans=0,returned,v;
    n=100000000; s=1232077670; p=126810854; q=1536183938; //26
    // n=100000000; s=569099406; p=1607140150; q=823906344; //31
    cin>>n>>s>>p>>q;
    unsigned long long i, a0=s, a=s, ap=0, k=0, kt=0;

    v=pow(2,31);
    for(i=0; i<n; i++){
        // a=(a*p+q)&v;
        a=(a*p+q);
        a=a%v;
        if((a==a0 || a==ap) && i!=0){
            k=i+1;
            break;
        }
        ap=a;
    }
    if (i==n) k=i;

    cout <<k<<endl;  
    return 0;
}

Disclaimer: The above Problem (Bit Array) is generated by Hacker Rank but the Solution is Provided by Sloth Coders. This tutorial is only for Educational and Learning Purpose.

Sloth Coders is a Learning Platform for Coders, Programmers and Developers to learn from the basics to advance of Coding of different langauges(python, Java, Javascript and many more).

Post a Comment