I was trying to solve this problem on hackerrank.
You are given four integers: N,S,P,Q. You will use them in order to create the sequence 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 .
Sample Input
3 1 1 1
Sample Output
3
Constraints
1<= N <= 10^8
0<= S,P,Q < 2^31
And this was my solution in c++.. Most of the times I was getting segmentation faults.. I know this was supposed to be solved using bit arrays.. but wanted to know why this wasnt working.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
unsigned long long n,s,p,q;
cin >> n >> s >> p >> q;
//declaring array to hold sequence
unsigned long long a[n];
// for loop termination
bool termination_check = true;
//initializing sequence
//s<2^31 hence, s modulo 2^31 is always s
a[0] = s;
//creating sequence
for(int i=1;i<n;i++){
//calculating next term of sequence..
a[i] = (a[i-1]*p)+q;
//since a[i] modulo 2^31 is a[i] when a[i] < 2^31
if(a[i]>=pow(2,31)){
a[i] = a[i]%31;
//when the current term matches with any of previous terms of sequence, then the
//terms just repeat after that (since p and q are constants)
for(int j=0;j<i;j++){
if(a[i]==a[j]){
cout <<i << endl;
//i was trying to use break but dont know why, it did not work
termination_check = false;
break;
break;
}
}
}
}
//if there was no termination of loop then all the terms are distinct
if(termination_check){
printf("%llu \n", n);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}