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 store numbers as vectors. Any number can be represented as a vector of digits// [ a0 , .. , an] = a0 + a1*10 + .. + an*10^n// During calculations I temporarily do not use a constraint that each number a0 .. an is a single digit. I restore it after the summations and multiplications are done// Transform integer to vectorvector<int>number_to_vector(intt){vector<int>ans;while(t!=0){ans.push_back(t%10);t=int(t/10);}returnans;}// Compute the sum of two integers represented as vectorsvector<int>my_sum_raw(constvector<int>&t1,constvector<int>&t2){intN1=t1.size();intN2=t2.size();intN=max(N1,N2);intcarry=0;vector<int>ans(N);for(inti=0;i<N;i++){inta=0;intb=0;if(i<N1)a=t1[i];if(i<N2)b=t2[i];ans[i]=a+b;}returnans;}// The most brute-force way to compute the square of a number represented by a vectorvector<int>my_square_2(constvector<int>&t){vector<int>ans(2*t.size());intcarry=0;for(inti=0;i<t.size();i++){// Notice, that here I am avoiding double-counting. Otherwise my code would not pass all testsfor(intj=i;j<t.size();j++){intx=t[i]*t[j];if(i!=j)x*=2;ans[i+j]+=x;}}returnans;}// Now I have got an answer represented as a vector [a0, .. , an], where the number isa0+a1*10+...+an*10^n.Ihadabandonedtheconstraintofeachnumberasasingledigit.Irestoreitattheend.vector<int>clean_ans(constvector<int>&t){vector<int>ans(t.size());inta=0;for(inti=0;i<ans.size();i++){a+=t[i];ans[i]=a%10;a=int(a/10);}while(a>0){ans.push_back(a%10);a=int(a/10);}while(ans[ans.size()-1]==0)ans.pop_back();returnans;}vector<int>fibonacciModified(intt1,intt2,intn){vector<int>vect_t1=number_to_vector(t1);vector<int>vect_t2=number_to_vector(t2);if(n==1)returnvect_t1;if(n==2)returnvect_t2;// Compute Fibonacci numbers using the conventional dynamic programming methodvector<int>vect_t3;for(inti=2;i<n;i++){vect_t3=clean_ans(my_sum_raw(vect_t1,my_square_2(vect_t2)));vect_t1=vect_t2;vect_t2=vect_t3;}returnvect_t3;}// At the end it is strange that the answer is too big to be int, but the return type of the function was int. I changed it to a vector. Therefore I had to change the print function toointmain(){ofstreamfout(getenv("OUTPUT_PATH"));stringfirst_multiple_input_temp;getline(cin,first_multiple_input_temp);vector<string>first_multiple_input=split(rtrim(first_multiple_input_temp));intt1=stoi(first_multiple_input[0]);intt2=stoi(first_multiple_input[1]);intn=stoi(first_multiple_input[2]);vector<int>result=fibonacciModified(t1,t2,n);for(inti=result.size()-1;i>=0;i--){fout<<result[i];}fout<<"\n";fout.close();return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Fibonacci Modified
You are viewing a single comment's thread. Return to all comments →