We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I have read the editorial. I find the explanation simple enough. However, I am still getting different answers from the tests. Test case 2: input: 761 99 1, result given by HackerRank: 236568308, result given by my code: 5776253194797940406
It is funny I should be getting different results because my code gives exactly same results when running against simple test cases using brute force.
I also wrote a method which had time out issues. This also gives 5776253194797940406 for input 761 99 1.
I also find it strange editorial talks about using Fermat's little Theorem when surely such optimization is done by the compiler?
longlongcountArray(intn,intk,intx){longlongretVal=1;/* f(i) num ways to fill range [1, i] such that A1 = 1 and Ai != 1 x != 1, answer is f(n)/(k - 1) x = 1, f(n - 1) f(i) = (k - 1)f(i - 2) + (k - 2)f(i - 1) */longlongf0=0;longlongf1=k-1;inti=2;while(++i<n){if((i%2)!=0){f0=(k-1)*f0+(k-2)*f1;}else{f1=(k-1)*f1+(k-2)*f0;}}if(x==1){if((n%2)!=0){retVal=f1;}else{retVal=f0;}}else{if((n%2)!=0){retVal=(k-1)*f0+(k-2)*f1;}else{retVal=(k-1)*f1+(k-2)*f0;}retVal/=(k-1);}returnretVal;}longlongPower(longlongx,longlongy){longlongretVal=x;for(inti=1;i<y;i++){retVal*=x;}returnretVal;}longlongcountArrayInefficient(intn,intk,intx){longlongretVal=1;longlongi=1;retVal=Power(k-1,n-2);longlongm=n-2;while(--m>0){i=-i;retVal+=i*Power(k-1,m);}if(x!=1){if((n%2)==0)retVal++;elseretVal--;}returnretVal;}longcountArrayBruteForce(intn,intk,intx){longretval=0;// crude method below:int*array=newint[n];array[0]=1;array[n-1]=x;inti=1;for(inti=1;i<n-1;i++)array[i]=1;boolend=false;intpos=n-2;while(!end){end=true;for(inti=1;i<n-1;i++){if(array[i]!=k){end=false;break;}}if(array[pos]==k){pos--;}else{array[pos]++;if(pos<n-2){pos++;array[pos]=0;}else{boolvalid=true;for(inti=1;i<n;i++){if(array[i]==array[i-1]){valid=false;break;}}if(valid){for(inti=0;i<n;i++){cout<<array[i]<<' ';}cout<<endl;retval++;}}}}delete[]array;returnretval;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Construct the Array
You are viewing a single comment's thread. Return to all comments →
I have read the editorial. I find the explanation simple enough. However, I am still getting different answers from the tests. Test case 2: input: 761 99 1, result given by HackerRank: 236568308, result given by my code: 5776253194797940406 It is funny I should be getting different results because my code gives exactly same results when running against simple test cases using brute force. I also wrote a method which had time out issues. This also gives 5776253194797940406 for input 761 99 1. I also find it strange editorial talks about using Fermat's little Theorem when surely such optimization is done by the compiler?