Skip to main content

Featured

say hello world with C++ - Solution in Hacker Rank - hackerranksolutions8

  Objective This is a simple challenge to help you practice printing to  stdout . You may also want to complete  Solve Me First  in C++ before attempting this challenge. We’re starting out by printing the most famous computing phrase of all time! In the editor below, use either  printf  or  cout  to print the string  Hello ,World!  to  stdout . The more popular command form is  cout . It has the following basic form: cout<<value_to_print<<value_to_print; Any number of values can be printed using one command as shown. The  printf  command comes from C language. It accepts an optional format specification and a list of variables. Two examples for printing a string are: printf("%s", string);   printf(string); Note that neither method adds a newline. It only prints what you tell it to. Output Format Print   Hello ,World!   to stdout. Sample Output Hello, World! Solution:- //Say Hello, ...

Bit Array in C++ – Solution in Hacker Rank - hackerranksolutions8

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^80 <= 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++ - Hacker Rank Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() 
{
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    /* Bit Array in C++ - Hacker Rank Solution */
    uint_fast64_t po = (uint_fast64_t)(pow(2, 31));
    uint_fast64_t N, S, P, Q;
    cin >> N >> S >> P >> Q;

    bool r = false;
    uint_fast64_t c = 0;
    uint_fast64_t prv = S % po;
    uint_fast64_t crn = -1;
    uint_fast64_t i = 1;

    do 
    {
        crn = (prv * P + Q) % po;
        if (crn != prv) 
        {
            prv = crn;
            ++c;
        } 
        else 
        {
            r = true;
        }
        ++i;
    } while (i < N && !r);
    cout << c + 1 << endl;
    /* Bit Array in C++ - Hacker Rank Solution */
    
    return 0;
}

 

Comments