私はこの問題をhackerrankで解決しようとしていました。符号なしlong long配列を使用できますか?
N、S、P、Qの4つの整数が与えられます。次の擬似コードでシーケンスを作成するためにそれらを使用します。
a[0] = S (modulo 2^31)
for i = 1 to N-1
a[i] = a[i-1]*P+Q (modulo 2^31)
あなたの仕事は、シーケンス内の別個の整数の数を計算することです。
Sample Input
3 1 1 1
Sample Output
3
Constraints
1<= N <= 10^8
0<= S,P,Q < 2^31
そして、これはC言語で私の解決策だっ++ ..私はセグメンテーションフォールトを得ていた時間の大半は、..私は、これはビットアレイを使用して解決することになっていた知っている..しかし、この波平が働い理由を知りたいと思いました。
#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;
}
「i」は「n」より小さい。 'j'を' i'に、 'i'''を' n'に設定します。だから 'j Benoit
タイトルは実際の問題と何が関係していますか? – sashoalm