HackerRank Gold Badge In C++ | All Problem Solution

HackerRank Gold Badge in C++ All Solutions

HackerRank Gold Badge In C++ | All Problem Solution is available here. Practice them and get a gold badge in C++ programming. Total 44 solved problems of hackerRank in C++. Solution of C++ hackerRank.

Join For More Challenge Solution & Updates

Say "Hello, World!" With C++

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    cout<<"Hello, World!"<<endl;
    //printf("Hello, World!");
    return 0;
}

Input and Output

#include <iostream>
using namespace std;

int main() {
    int a,b,c;
    cin>>a>>b>>c;
    cout<<a+b+c<<endl;
    return 0;
}

Basic Data Types

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a; long b; char c; float d; double e;
    cin>>a>>b>>c>>d>>e;
    cout<<a<<endl<<b<<endl<<c<<endl;
    cout<<fixed<<setprecision(3)<<d<<endl;
    cout<<fixed<<setprecision(9)<<e<<endl;
    return 0;
}

Conditional Statements

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n,c=0;
    string a[]={"one","two","three","four","five","six","seven","eight","nine"};
    cin>>n;
    if(n>9){
        cout<<"Greater than 9"<<endl;
    }
    else{
        for(int i=1;i<n;i++){
            c++;
        }
        cout<<a[c]<<endl;
    }
}

For Loop

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a,b;
    string c[]={"","one","two","three","four","five","six","seven","eight","nine"};
    cin>>a>>b;
    for(int i=a;i<=b;i++)
        cout<<((i<=9)?c[i]:((i%2==0)?"even":"odd"))<<endl;
}

Functions

#include <iostream>
using namespace std;
#include <algorithm>

int main() {
    int a[4];
    for(int i=0;i<4;i++){
        cin>>a[i];
    }
    sort(a,a+4);
    cout<<a[3]<<endl;

    
    return 0;
}

Pointers

#include <stdio.h>

void update(int *a,int *b) {
    int sum = *a + *b;
    int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
    *a = sum;
    *b = absDifference; 
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);
    return 0;
}

Arrays Introduction

#include <iostream>
using namespace std;
int main() {
    int N,i=0;
    cin>>N;
    int a[N];
    for(int i=0;i<N;i++){
        cin>>a[i];
    }
    for(int i=N-1;i>=0;i--){
        cout<<a[i]<<" ";
    }
    return 0;
}

Variable Sized Arrays

#include<iostream>
using namespace std;
#include<bits/stdc++.h>
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n, q, size, value, which, index;
    cin >> n >> q;
    vector<vector<int>> nvec;
    for (int i = 0; i < n; ++i) {
        cin >> size;
        vector<int> ivec;
        for (int j = 0; j < size; ++j) {
            cin >> value;
            ivec.push_back(value);
        }
        nvec.push_back(ivec);
    }
    for (int k = 0; k < q; ++k) {
        cin >> which >> index;
        cout << nvec[which][index] << endl;
    }
    return 0;
}

Attribute Parser

#include <iostream>
#include <map>
using namespace std;

map <string, string> tagMap;

void createMap(int &n, string pretag) {
    if(!n) return;
    
    string line, tag, attr, value;
    getline(cin, line);
    
    int i=1;
    if(line[i]=='/') {           // found closing tag
        while(line[i]!='>') i++;
        if(pretag.size()>(i-2))		// update tag
            tag = pretag.substr(0,pretag.size()-i+1);
        else
            tag = "";
    }
    else {                       // found opening tag
        while(line[i]!=' ' && line[i]!='>') i++;
        tag = line.substr(1,i-1);	// update tag
        if(pretag!="") tag = pretag + "." + tag;
        
        int j;
        while(line[i]!='>') { // go through attributes
            j = ++i;
            while(line[i]!=' ') i++;
            attr = line.substr(j,i-j);	// attribute name
            
            while(line[i]!='\"') i++;
            j = ++i;
            while(line[i]!='\"') i++;
            value = line.substr(j,i-j);	// attribute value
            i+= 1;
            
            tagMap[tag + "~" + attr] = value;
        }
    }
    createMap(--n, tag);
}

int main() {
    int n, q;
    cin >> n >> q;
    cin.ignore();
    createMap(n,"");
    
    string attr, value;
    while(q--) {
        getline(cin,attr);
        value = tagMap[attr];
        if(value=="") value = "Not Found!";
        cout << value << endl;
    }
    return 0;
}

StringStream

#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

vector<int> parseInts(string str) {
   vector<int> ret;
   int a;
   char ch;
   stringstream s; 
   s.str(str);
   while(!s.eof()) {
       s >> a;
       ret.push_back(a);
       s >> ch;
   }
   return ret;
}

int main() {
    string str;
    cin >> str;
    vector<int> integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) {
        cout << integers[i] << "\n";
    }
    
    return 0;
}

Strings

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string a, b;
    cin >> a >> b;
    
    cout << a.length() << ' ' << b.length() << endl;
    
    cout << a + b << endl;
    
    swap( a[0], b[0] );
    cout << a << ' ' <<  b << endl;
    
    return 0;
}

Structs

#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;

struct Student
{
    unsigned age{};
    string first_name{};
    string last_name{};
    unsigned standard{};
};
int main() {
    Student st;
    
    cin >> st.age >> st.first_name >> st.last_name >> st.standard;
    cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard;
    
    return 0;
}

Class

#include <iostream>
#include <sstream>
using namespace std;

class Student{
    private:
    
    int age;
    int standard;
    string first_name;
    string last_name ;

    public:

    // setter
    void set_age(int ageV){
        age = ageV;
    }
    void set_standard(unsigned standardV){
        standard = standardV;
    }
    void set_first_name(string firstName){
        first_name = firstName;
    }
    void set_last_name(string lastName){
        last_name = lastName;
    }

    // getter
    int get_age(){
        return age;
    }
    int get_standard(){
        return standard;
    }
    string get_first_name(){
        return first_name;
    }
    string get_last_name(){
        return last_name;
    }

    string to_string(){
        string result = std::to_string(age) +','+get_first_name()+','+get_last_name()+','+std::to_string(standard);
        return result;
    }

};

int main() {
    int age, standard;
    string first_name, last_name;
    
    cin >> age >> first_name >> last_name >> standard;
    
    Student st;
    st.set_age(age);
    st.set_standard(standard);
    st.set_first_name(first_name);
    st.set_last_name(last_name);
    
    cout << st.get_age() << "\n";
    cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
    cout << st.get_standard() << "\n";
    cout << "\n";
    cout << st.to_string();
    
    return 0;
}

Classes and Objects

class Student {
  private:
    int scores[5];
    int sum;
  public:
    Student() : sum(0) {}
    int calculateTotalScore() {return sum;}
    void input() {
        for(int i=0; i<5; i++) {
            cin >> scores[i];
            sum+=scores[i];
        }
    }
};

Box It

class Box{
    private:
    int l, b, h;
    public:
    Box(){
        l = 0;
        b = 0;
        h = 0;
    }
    Box(int length, int breadth, int height){
        l = length;
        b = breadth;
        h = height;
    }
    Box(const Box& B){
        l = B.l;
        b = B.b;
        h = B.h;
    }
    
    int getLenght(){
        return l;
    }
    int getBreadth(){
        return b;
    }
    int getHeight(){
        return h;
    }
    long long CalculateVolume(){
        return (long long)l*b*h;
    }
    
    friend bool operator < ( Box&A,Box& B){
        if( (A.l < B.l) || ((A.b < B.b) && (A.l == B.l)) || ((A.h < B.h) && (A.l == B.l) && (A.b == B.b)) ){
            return true;
        }else{
            return false;
        }
    };
    
    friend ostream& operator<< (ostream& output, const Box& B){
        output << B.l << " " << B.b << " " << B.h;
        return output;
    }
};

Inherited Code

class BadLengthException {
    private: 
        int n;
    public:
        BadLengthException(int errornumber) {
            n = errornumber;
        }
    
        int what() {
            return n;
        }

Exceptional Server

    try {
        if (A > 1073741823LL) {
            Server::compute(2, 1);
            throw bad_alloc();
        }
        cout << Server::compute(A, B) << '\n';
    }
    catch (bad_alloc &e) {
        cout << "Not enough memory\n";
    }
    catch (exception &e) {
        cout << "Exception: " << e.what() << '\n';
    }
    catch (...) {
        cout << "Other Exception\n";
    }

Virtual Functions

class Person {
public:
    string name;
    int age;
    virtual void getdata() {
        cin >> this->name >> this->age;
    }
    virtual void putdata() {
        cout << this->name << " " << this->age << endl;
    }
};

class Professor : public Person {
public:
    Professor() {
        this->cur_id = ++id;
    }
    int publications;
    static int id;
    int cur_id;
    void getdata() {
        cin >> this->name >> this->age >> this->publications;
    }
    void putdata() {
        cout << this->name << " "
            << this->age << " "
            << this->publications << " "
            << this->cur_id << endl;
    }
};
int Professor::id = 0;

class Student : public Person {
#define NUM_OF_MARKS 6
public:
    Student() {
        this->cur_id = ++id;
    }
    int marks[NUM_OF_MARKS];
    static int id;
    int cur_id;
    void getdata() {
        cin >> this->name >> this->age;
        for (int i=0; i<NUM_OF_MARKS; i++) {
            cin >> marks[i];
        }
    }
    void putdata() {
        int marksSum = 0;
        for (int i=0; i<NUM_OF_MARKS; i++) {
            marksSum += marks[i];
        }
        cout << this->name << " "
            << this->age << " "
            << marksSum << " "
            << this->cur_id << endl;
    }
};
int Student::id = 0;

Abstract Classes - Polymorphism

#include <list>
#define key first
#define val second
class LRUCache {
    int cp;
    map<int, list<pair<int, int> >::iterator> mp;
    list<pair<int, int> > lru;
public:
    LRUCache(int capacity) : cp(capacity){}
    void set(int key, int val) {
        if(mp.find(key) != mp.end()) {
            mp[key]->key = key;
            mp[key]->val = val;
        }
        else {
            lru.push_front({key, val});
            mp[key] = lru.begin();
            if(lru.size() > cp) {
                mp.erase(lru.back().key);
                lru.pop_back();
            }
        }
    }
    int get(int key) {
        if(mp.find(key) != mp.end()) {
            lru.push_front(*mp[key]);
            lru.erase(mp[key]);
            mp[key] = lru.begin();
            return mp[key]->val;
        }
        else
            return -1;
    }
};

Vector-Sort

#include<bits/stdc++.h>
#include <iostream>
using namespace std;


int main() {
    vector<int>vec;
    int n, nums;
    cin >> n;
    
    while (cin >> nums) 
    vec.push_back(nums);
 
    sort(vec.begin(), vec.end());
    
    for(int i=0; i<n; i++)
    cout << vec[i] << " "; 
    return 0;
}

Vector-Erase

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


int main() {
    int N, a, x, b, c;
    vector<int> v;
    cin >> N;
    for (int i = 0; i < N; i++) {
        cin >> a;
        v.push_back(a);
    }
    cin >> x >> b >> c;
    v.erase(v.begin() + x - 1);
    v.erase(v.begin() + b - 1, v.begin() + c - 1);
    cout << v.size() << endl;
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
    return 0;
}

Lower Bound-STL

#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 */
    int n;
    vector<int> vec;
    cin >> n;
    for (int i = 0; i < n; i++) {
        int temp;
        cin >> temp;
        vec.push_back(temp);
    }
    int q;
    cin >> q;
    for (int i = 0; i < q; i++) {
        int temp;
        cin >> temp;
        vector<int>::iterator iter;
        iter = lower_bound(vec.begin(), vec.end(), temp);
        if (*(iter + 1) == temp || *iter == temp)
            cout << "Yes " << iter - vec.begin() + 1 << endl;
        else
            cout << "No " << iter - vec.begin() + 1 << endl;
    }
    return 0;
}

Sets-STL

#include<bits/stdc++.h>
using namespace std;
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int q, n, i, j, y, x;
    cin >> q;
    set<int> s;
    for (i=0;i<q;i++) {
        cin >> y >> x;
        if (y == 1) {
            s.insert(x);
        }
        if (y ==2) {
            s.erase(x);
        }
        if (y == 3) {
            set<int>::iterator itr = s.find(x);
            if (itr != s.end()) cout << "Yes" << endl;
            //if (*itr == x) cout << "Yes" << endl;
            else cout << "No" << endl;
        }
    }
    return 0;
}

Maps-STL

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


int main() {
    int q, type; cin >> q; 
    map<string,int> clas; string name;
    for (int i(0), mark; i<q; ++i)
    {
        cin >> type >> name;
        if (type == 1){
            cin >> mark;
            clas[name] += mark;
        }
        else if (type == 2)
            clas.erase(name);
        else
            cout << clas[name] << "\n";
    }
    return 0;
}

Print Pretty

    /* Enter your code here */
        // LINE 1 
        cout << hex << left << showbase << nouppercase; // formatting
        cout << (long long) A << endl; // actual printed part

        // LINE 2
        cout << dec << right << setw(15) << setfill('_') << showpos << fixed << setprecision(2); // formatting
        cout << B << endl; // actual printed part

        // LINE 3
        cout << scientific << uppercase << noshowpos << setprecision(9); // formatting
        cout << C << endl; // actual printed part

Deque-STL

#include <iostream>
#include <deque> 
using namespace std;

void printKMax(int arr[], int n, int k){
    //Write your code here.
    deque<int> dq;
    
    for (int i=0; i<n; i++){
        
        // base case for first element
        if (dq.empty()){
            dq.push_back(i);
        }
        
        // remove elements outside the current window
        if (dq.front() <= (i - k)){
            dq.pop_front();
        }
        
        // move max element to the front
        while (!dq.empty() && arr[i] >= arr[dq.back()]){
            dq.pop_back();
        }
        
        dq.push_back(i);
        
        // print out only when the first window is completed
        if (i >= (k - 1)){
            cout << arr[dq.front()] << " ";
        }    
    }
    cout << endl;
}

int main(){
  
    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
              cin >> arr[i];
        printKMax(arr, n, k);
        t--;
      }
      return 0;
}

Inheritance Introduction

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


class Triangle
{
        public:

            void triangle()
                {
                cout<<"I am a triangle\n";
            }
};

class Isosceles : public Triangle
{
        public:

            void isosceles()
                {
                cout<<"I am an isosceles triangle\n";
            }

                void description()
                {
                        cout<<"In an isosceles triangle two sides are equal\n";
                }
};

int main(){
    Isosceles isc;
    isc.isosceles();
  	isc.description();
    isc.triangle();
    return 0;
}

Hotel Prices

#include <iostream>
#include <vector>

using namespace std;

class HotelRoom 
{
    public:

        HotelRoom(int bedrooms, int bathrooms)
        : bedrooms_(bedrooms), bathrooms_(bathrooms) 
        {

        }

        virtual int get_price() 
        {
                return ((50 * bedrooms_) + (100 * bathrooms_));
        }

    private:

        int bedrooms_;
        int bathrooms_;
};

class HotelApartment : public HotelRoom {
public:
    HotelApartment(int bedrooms, int bathrooms) 
    : HotelRoom(bedrooms, bathrooms) {}

    int get_price() {
        return HotelRoom::get_price() + 100;
    }
};

Cpp exception handling

void process_input(int n) {
    try {
        int d = largest_proper_divisor(n);
        cout << "result=" << d << endl;
    } catch (const invalid_argument& e) {
        cout << e.what() << endl;
    }
    cout << "returning control flow to caller" << endl;
}

Rectangle Area

using namespace std;
/*
 * Create classes Rectangle and RectangleArea
 */
 class Rectangle {
public:
    virtual void display() const {
        cout << width << ' ' << height << endl;
    }
    
protected:
    int width;
    int height;
};

class RectangleArea : public Rectangle {
public:
    void display() const override {
        cout << (width * height) << endl;
    }
    
    void read_input() {
        cin >> width >> height;
    }
};

Multi Level Inheritance

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

class Triangle{
	public:
		void triangle(){
			cout<<"I am a triangle\n";
		}
};

class Isosceles : public Triangle{
  	public:
  		void isosceles(){
    		cout<<"I am an isosceles triangle\n";
  		}
};

//Write your code here.
class Equilateral : public Isosceles
{
    public:
        void equilateral(){
            cout << "I am an equilateral triangle" << endl;
        }
};

int main(){
  
    Equilateral eqr;
    eqr.equilateral();
    eqr.isosceles();
    eqr.triangle();
    return 0;
}

Overloading Ostream Operator

// Enter your code here.
ostream& operator<<(ostream& os, const Person& pr)  
{  
    os <<"first_name=" <<pr.get_first_name() << ",last_name=" << pr.get_last_name();  
    return os;  
}  

Messages Order

class Message {
private:
    string text;
    static int id;
    int current_id;
public:
    Message() { current_id = ++id; }
    Message(string t){ current_id = ++id; text=t; }
    const string& get_text() {
        return text;
    }
    // overloaded < operator
    bool operator < (const Message& M2) {
        if(current_id < M2.current_id)
            return true;
        else
            return false;
    }
};
int Message::id = 0;

class MessageFactory {
public:
    MessageFactory() {}
    Message create_message(const string& text) {
        Message m = Message(text);
        return m;
    }
};

Accessing Inherited Functions

class D : public A, public B, public C
{

    int val;
    public:
         D()
         {
             val = 1;
         }

         void update_val(int new_val)
         {
            while(new_val%2 == 0) {
                A::func(val);
                new_val /= 2;
            }
            while(new_val%3 == 0) {
                B::func(val);
                new_val /= 3;
            }
            while(new_val%5 == 0) {
                C::func(val);
                new_val /= 5;
            }
         }
         //For Checking Purpose
         void check(int); //Do not delete this line.
};

Magic Spells

  if (Fireball *fb = dynamic_cast<Fireball*>(spell))
    {
        fb->revealFirepower();
    }
    else if (Frostbite *fb = dynamic_cast<Frostbite*>(spell))
    {
        fb->revealFrostpower();
    }
    else if (Thunderstorm *ts = dynamic_cast<Thunderstorm*>(spell))
    {
        ts->revealThunderpower();
    }
    else if (Waterbolt *wb = dynamic_cast<Waterbolt*>(spell))
    {
        wb->revealWaterpower();
    }
    else
    {
        std::string strA = spell->revealScrollName();
        std::string strB = SpellJournal::read();
   
    int m = strA.length();
    int n = strB.length();

    std::vector<std::vector<int>> vLCSMatrix(m + 1, std::vector<int>(n + 1));

    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (strA[i - 1] == strB[j - 1])
            {
                vLCSMatrix[i][j] = 1 + vLCSMatrix[i - 1][j - 1];
            }
            else
            {
                vLCSMatrix[i][j] = std::max(vLCSMatrix[i - 1][j], vLCSMatrix[i][j - 1]);
            }
        }
    }

     std::cout << vLCSMatrix[m][n] << std::endl;
    }

C++ Class Templates

template <class T>
class AddElements {
    T element;
  public:
    AddElements (T arg) {element=arg;}
    T add (T x) {return x+element;}
};

// class template specialization:
template <>
class AddElements <string> {
    string element;
  public:
    AddElements (string arg) {element=arg;}
    string concatenate (string arg)
    {
      string s = element+arg;
      return s;
    }
};

Preprocessor Solution

#define INF (unsigned)!((int)0)
#define FUNCTION(name,operator) inline void name(int &current, int candidate) {!(current operator candidate) ? current = candidate : false;}
#define io(v) cin>>v
#define toStr(str) #str
#define foreach(v, i) for (int i = 0; i < v.size(); ++i)

Operator Overloading

class Matrix{

public:
vector<vector<int> > a;

Matrix & operator + (const Matrix &y) {

    for (int m=0; m<y.a.size(); ++m) {
        for (int n=0; n<y.a[0].size(); ++n) {
            this->a[m][n] = this->a[m][n] + y.a[m][n];
        }
    }

    return *this;
}
};

Operator Overloading

ostream& operator<<(ostream& os, const Complex& c) {
    return os << c.a << (c.b > 0 ? '+' : '-') << 'i' << c.b;
}

Complex operator+(const Complex& a, const Complex& b) { 
    return { a.a + b.a, a.b + b.b };
}

Overload Operators

class Matrix{

public:
vector<vector<int> > a;

Matrix & operator + (const Matrix &y) {

    for (int m=0; m<y.a.size(); ++m) {
        for (int n=0; n<y.a[0].size(); ++n) {
            this->a[m][n] = this->a[m][n] + y.a[m][n];
        }
    }

    return *this;
}
};

Attending Workshops

#include <vector>

struct Workshop {
  int start_time;
  int duration;
  int end_time;
};

struct Available_Workshops {
  int n;
  vector<Workshop> workshops;
};

Available_Workshops* initialize(int start_time[], int duration[], int n) {
  Available_Workshops* aw{new Available_Workshops};
  aw->n = n;

  for (int i = 0; i < n; i++) {
    Workshop w;
    w.start_time = start_time[i];
    w.duration = duration[i];
    w.end_time = w.start_time + w.duration;
    aw->workshops.push_back(w);
  }

  return aw;
}

bool compare_workshops(Workshop& w1, Workshop& w2) {
  return w1.end_time - w2.end_time > 0;
}

int CalculateMaxWorkshops(Available_Workshops* ptr) {
  vector<Workshop> workshops = ptr->workshops;
  sort(workshops.begin(), workshops.end(), compare_workshops);


  int total{0};
  while (workshops.size()) {
    ++total;
    int end_time = workshops.back().end_time;
    bool overlap{true};
    while (workshops.size() && overlap) {
      workshops.pop_back();
      if (workshops.back().start_time >= end_time) {
        overlap = false;
      }
    }
  }

  return total;
}

C++ Class Template Specialization

template <> 
struct Traits<Fruit>{
    static string name(int index){
        switch(index){
                case 0:return "apple";
                case 1: return "orange" ;
                case 2: return "pear";
        }  
        return "unknown";
    } 
};
template <> 
struct Traits<Color>{
    static string name(int index){
        switch(index){
                case 0:return "red";
                case 1: return "green" ;
                case 2: return "orange";           
        }
        return "unknown";  
    } 
};

C++ Variadics

template <bool a> int reversed_binary_value() { return a; }

template <bool a, bool b, bool... d> int reversed_binary_value() {
  return (reversed_binary_value<b, d...>() << 1) + a;
}

Bit Array

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <bitset>
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

    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;
}

Here is the all 44 solution of C++. You can understand and learn it from a single place easily. Do comment for more solutions and solved challenges.

Join For More Challenge Solution & Updates

Leave a Comment

Your email address will not be published. Required fields are marked *

0

Tech Info