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 agree. Choose a language that has large number support and you can just translate the formula into code and are done. It becomes almost as simple as hello world.
use double to declare data type as double a ,b,c;
while scaning scanf("%lf",&a);
while printing printf("%0.lf",a); // 0.lf restricts the decimal point to zeroth position which is an integer
u have to convert number into array/string, like if number is 543656 then store it in array like |3|4|3|6|5|6|. then write seperate function to add and multiply these array/string and then try to find out fibo.
double will not work.. The no. is too large. If you are doing in Java, there is a datatype for very large no. but in C, you have to take the no. as string and do the addition of two no.s by writing a function for addition of two strings.
Can you tell us which testcase is giving seg fault?
You can just download that testcase and check yourself too.
It must be an edge case or might be using enormous memory.
I get this awesome interesting and unique game which is online and you will love word unscrambler play by using special skills to win this Online Multiplayer game.
Although simple enough, I think it still uses the thoguht of DP - it keeps recording the two former numbers and build the solution from bottom to top, instead of recurring from top to bottom, which would lead to a huge number of unnecessary function calls.
Well you could do that, but you don't need to. I submitted a solution using dynamic programming, and one using just regular recursion. The difference in running time is so small that it prints the same running times, even though one runs in linear time and the other one in exponential time. They should increase the test size and limit the amount of running time so that without the use of dynamic programming you can't solve the problem imo.
static String fibonacciModified(int t1, int t2, int n) {
BigInteger c=new BigInteger("0");
BigInteger a=new BigInteger(t1+"");
BigInteger b=new BigInteger(t2+"");
for (int i=0;i
{
c=a.add(b.multiply(b));
a=b;
b=c;
}
return c.toString();
}**
I hope this will help you
publicclassSolution{publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */inti,n;BigIntegera,b;Scannersc=newScanner(System.in);a=sc.nextBigInteger();b=sc.nextBigInteger();n=sc.nextInt();BigInteger[]val=newBigInteger[n];val[0]=a;val[1]=b;for(i=2;i<n;i++){val[i]=(val[i-1].pow(2)).add(val[i-2]);}System.out.println(val[i-1]);}}
Solution.java:6: error: cannot find symbol
BigInteger a,b;
^
symbol: class BigInteger
location: class Solution
Solution.java:7: error: cannot find symbol
Scanner sc=new Scanner(System.in);
^
symbol: class Scanner
location: class Solution
Solution.java:7: error: cannot find symbol
Scanner sc=new Scanner(System.in);
^
symbol: class Scanner
location: class Solution
Solution.java:11: error: cannot find symbol
BigInteger [] val = new BigInteger[n];
^
symbol: class BigInteger
location: class Solution
Solution.java:11: error: cannot find symbol
BigInteger [] val = new BigInteger[n];
^
symbol: class BigInteger
location: class Solution
5 errors
I solved it with recursion. Probably stupid but the problem is defined recursively so it was the first thing that popped in my mind. If you memoize the recursive calls it needn´t be terribly inefficient.
The point of doing it in DP and not in recursion is that recursion takes a lot of time while DP doesnt. Doesnt make any sense doing it in recursion as it is said to do it in dp.
DP comes from Dynamic Programming, is an algorithm paradigm or a technique to solve complex problems breaking them into small ones. Just like you I still do not have any idea about what it is or how to implemented. If you find any DP course for dummies, please let me know, the ones I've found are a little bit difficult to follow.
You are calculating tn by solving the problem from t1 to tn, and recording the results in order to calculate the one you need.
That's the whole idea of dynamic programming: to solve a complex instance of a problem using the solution to smaller instances.
This problem is so simple that you can't really appreciate the technique. If you want an example of a more "serious" DP algorithm, you might look to a classic like the Wagner–Fischer algorithm to compute the distance between strings. It's simple enough but not trivial.
AFAIK, there's no easy way to do this problem in C++ with the libraries provided. In real life you'd use a bignum library like GNU MP or Boost.Multiprecision, but those libraries aren't available here.
You can certainly roll your own, but that seems a little extreme.
I've done all the other algorithm problems in C++, but for this one I switched to Java so I could use java.math.BigInteger.
I passed all tests by using the Karatsuba multiplication algorithm with my own Big Integer implementation. Very dumb by the way, but fast enough to find the 24 modified Fibonacci number in a half of second (0 1 24).
Nothing special work was done about working with number representation – store it as is in a base 10 in a vector. If it is still relevant for you, email me (taenaru@gmail.com) and I'll gladly explain you how it might work.
It's a waste of dev time, imho. Karatsuba algo replaces 2mul+1add with 1mul+4add. They say mul takes 3-4 times cycles of add these days, so you gonna get max 12.5% speed up (or zero, if it's actually 3 times) for the code which probably takes less than 20% of execution time (memory access will be the bottleneck, not number crunching)
Totally agree. This really shouldn't be categorized as a dynamic programming problem. Without having to worry about big numbers the solution is trival.
For people using C#, just use System.Numerics.BigInteger.
Tried doing it with strings. But, it TLE'd on 4 test cases! T_T
#include<bits/stdc++.h>usingnamespacestd;#define ll long long#define PI 3.1415926535897932384626#define pb push_back#define mp make_pair#define F first#define S second#define br '\n'#define FOR(i, a, b) for(int i=int(a);i<=int(b);++i)#define FORR(i, a, b) for(int i=int(a);i>=int(b);--i)#define TR(it, x) for(auto it = x.begin(); it != x.end(); it++)#define TRR(it, x) for(auto it = x.rbegin(); it != x.rend(); it++)#define deb(x) cout<<#x<<"-"<<x<<"\n"typedefpair<int,int>pii;typedefpair<float,float>pff;typedefvector<int>vi;typedefvector<float>vf;typedefvector<pii>vpii;typedefvector<vi>vvi;typedefstack<int>si;typedefqueue<int>qi;mt19937_64rang(chrono::high_resolution_clock::now().time_since_epoch().count());constintmod=1e7;constintMAX=1e8;/* ========== START HERE ========= */stringmultiply(stringnum1,stringnum2){intn1=num1.size();intn2=num2.size();if(n1==0||n2==0)return"0";vector<int>result(n1+n2,0);inti_n1=0;inti_n2=0;for(inti=n1-1;i>=0;i--){intcarry=0;intn1=num1[i]-'0';i_n2=0;FORR(j,n2-1,0){intn2=num2[j]-'0';intsum=n1*n2+result[i_n1+i_n2]+carry;carry=sum/10;result[i_n1+i_n2]=sum%10;i_n2++;}if(carry>0)result[i_n1+i_n2]+=carry;i_n1++;}inti=result.size()-1;while(i>=0&&result[i]==0)i--;if(i==-1)return"0";strings="";while(i>=0)s+=std::to_string(result[i--]);returns;}stringfindSum(stringstr1,stringstr2){if(str1.length()>str2.length())swap(str1,str2);stringstr="";intn1=str1.length(),n2=str2.length();reverse(str1.begin(),str1.end());reverse(str2.begin(),str2.end());intcarry=0;for(inti=0;i<n1;i++){intsum=((str1[i]-'0')+(str2[i]-'0')+carry);str.push_back(sum%10+'0');carry=sum/10;}FOR(i,n1,n2-1){intsum=((str2[i]-'0')+carry);str.push_back(sum%10+'0');carry=sum/10;}if(carry)str.push_back(carry+'0');reverse(str.begin(),str.end());returnstr;}stringfibonacci_modified(stringt1,stringt2,intn){stringdp[n+1];dp[1]=t1;dp[2]=t2;FOR(i,3,n){dp[i]=findSum(multiply(dp[i-1],dp[i-1]),dp[i-2]);}returndp[n];}voidsolve(){stringt1,t2;intn;cin>>t1>>t2>>n;cout<<fibonacci_modified(t1,t2,n);}/* ========== THE MAIN ========= */intmain(){ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);srand(chrono::high_resolution_clock::now().time_since_epoch().count());intt=1;//scanf("%d",&t);while(t--){solve();}returnEXIT_SUCCESS;}
Fibonacci Modified
You are viewing a single comment's thread. Return to all comments →
My only concern is problem focusses on handling very large numbers rather than putting it under DP
I agree. Choose a language that has large number support and you can just translate the formula into code and are done. It becomes almost as simple as hello world.
I want to code in c itself. Any way out ?
Yes, Write functions for string multiplication and summation.
how to do that... plz can u explain??
use double to declare data type as double a ,b,c; while scaning scanf("%lf",&a); while printing printf("%0.lf",a); // 0.lf restricts the decimal point to zeroth position which is an integer
thank you.. thanks allloott... :)
Very easy problem for python users.
Hackerrank - Fibonacci Modified Solution
i tried that too. even used long double. that's not working.. can u explain?
in second test case its a 20 digit and crossing number soo long double is not enough to perform tis programme
u have to convert number into array/string, like if number is 543656 then store it in array like |3|4|3|6|5|6|. then write seperate function to add and multiply these array/string and then try to find out fibo.
can u help? what is wrong with this????
void fibonacciModified(double t1, double t2, double n) { int i; double arr[20]; arr[0]=t1; arr[1]=t2; for(i=2;i<20;i++) { arr[i]=t1+t2*t2; t1=t2; t2=arr[i]; } for(i=0;i<20;i++) { if((i+1)==n) printf("%0.lf",arr[i]); } }
double will not work.. The no. is too large. If you are doing in Java, there is a datatype for very large no. but in C, you have to take the no. as string and do the addition of two no.s by writing a function for addition of two strings.
use python or java big integer because double will not work
thanks buddy
i wrote it in c..its giving correct output in devcpp,but here it shows wrong output..
programing with the combination of codes and notes can always help. what is the meaning of the sentence like "a[i]-'0'"?
converting char a[i] to its decimal equivalent
same issue getting correct output in my IDE but segmentation fault while submittin... any suggestion?
Can you tell us which testcase is giving seg fault? You can just download that testcase and check yourself too. It must be an edge case or might be using enormous memory.
I get this awesome interesting and unique game which is online and you will love word unscrambler play by using special skills to win this Online Multiplayer game.
Very easy problem for python users.
Hackerrank - Fibonacci Modified Solution
agreee
Although simple enough, I think it still uses the thoguht of DP - it keeps recording the two former numbers and build the solution from bottom to top, instead of recurring from top to bottom, which would lead to a huge number of unnecessary function calls.
Well you could do that, but you don't need to. I submitted a solution using dynamic programming, and one using just regular recursion. The difference in running time is so small that it prints the same running times, even though one runs in linear time and the other one in exponential time. They should increase the test size and limit the amount of running time so that without the use of dynamic programming you can't solve the problem imo.
This problem doesn't even need recursion.. a for loop can solve this problem too
Yes, BigInteger in for loop will solve it.
how u sloved big integer in for loop??can u explain?
Here is the snippet,
y is it necessary to add "" while initializing the constructor of biginteger ?
Because BigInteger doesn't take int in its constructor but can take a string .So adding "" makes a integer , string .
A nice way is to use valueOf() function of BigInteger class.
oh thank u
why not use:
directly?
my code was correct but how to use biginteger from your code i understands
thanks
Compile time error
Compile Message
Solution.java:6: error: cannot find symbol BigInteger a,b; ^ symbol: class BigInteger location: class Solution Solution.java:7: error: cannot find symbol Scanner sc=new Scanner(System.in); ^ symbol: class Scanner location: class Solution Solution.java:7: error: cannot find symbol Scanner sc=new Scanner(System.in); ^ symbol: class Scanner location: class Solution Solution.java:11: error: cannot find symbol BigInteger [] val = new BigInteger[n]; ^ symbol: class BigInteger location: class Solution Solution.java:11: error: cannot find symbol BigInteger [] val = new BigInteger[n]; ^ symbol: class BigInteger location: class Solution 5 errors
I solved it with recursion. Probably stupid but the problem is defined recursively so it was the first thing that popped in my mind. If you memoize the recursive calls it needn´t be terribly inefficient.
Can you post your recursive solution, please.
This is not DP. Its plain Recursion.
The point of doing it in DP and not in recursion is that recursion takes a lot of time while DP doesnt. Doesnt make any sense doing it in recursion as it is said to do it in dp.
Yes, but memoized recursion can give similar results to DP with only slight overhead (e.g. here).
recurssion with memoziation is same as iterative
I did it using a simple loop and I don't even know what DP is. Could you please show me what a solution using DP looks like?
DP comes from Dynamic Programming, is an algorithm paradigm or a technique to solve complex problems breaking them into small ones. Just like you I still do not have any idea about what it is or how to implemented. If you find any DP course for dummies, please let me know, the ones I've found are a little bit difficult to follow.
https://www.youtube.com/watch?v=P8Xa2BitN3I Check this video out, it might be helpful if you want to understand the basics of Dynamic programming.
Your solution is a DP solution.
You are calculating tn by solving the problem from t1 to tn, and recording the results in order to calculate the one you need.
That's the whole idea of dynamic programming: to solve a complex instance of a problem using the solution to smaller instances.
This problem is so simple that you can't really appreciate the technique. If you want an example of a more "serious" DP algorithm, you might look to a classic like the Wagner–Fischer algorithm to compute the distance between strings. It's simple enough but not trivial.
Yeah, Python makes this problem pretty trivial
True, I switched from JavaScript just to get it done.. did find a pitfall though.
will produce weird numbers from the 8th iteration.
instead must use: second*second + first
That's because
math.pow()
will use floating-point numbers. It is more typically used when the power is a real number, not (necessarily) an integer.To raise integers to an integer power, use the exponentiation operator
**
:(Of course to compute a square of
x
,x*x
works just fine as well.)can u pls explain how to handle big integer in c++.
AFAIK, there's no easy way to do this problem in C++ with the libraries provided. In real life you'd use a bignum library like GNU MP or Boost.Multiprecision, but those libraries aren't available here.
You can certainly roll your own, but that seems a little extreme.
I've done all the other algorithm problems in C++, but for this one I switched to Java so I could use java.math.BigInteger.
ohk.thank you
Here is how I do it. You can actually make it faster by playing with Base.
well done man
Please can you explain your code
I'm sorry, I got lost in the conversation, which code?
you are awesome man
include
include
include
include
int main() { int i=2,x,y,n; int z,a[100]={0}; scanf("%d %d %d",&x,&y,&n);
{ z=0; z=x+pow(y,2); x=y; y=z; i++; a[z]+=z; }
printf("%d",a[z]); return 0; }
this my code it is displaying segementation error can anyone help me in getting the actual bug in this code
I barely know a thing or two about that ostream operator,great work man!!
I passed all tests by using the Karatsuba multiplication algorithm with my own Big Integer implementation. Very dumb by the way, but fast enough to find the 24 modified Fibonacci number in a half of second (0 1 24). Nothing special work was done about working with number representation – store it as is in a base 10 in a vector. If it is still relevant for you, email me (taenaru@gmail.com) and I'll gladly explain you how it might work.
can you send me explaination
nickholden786@gmail.com
It's a waste of dev time, imho. Karatsuba algo replaces 2mul+1add with 1mul+4add. They say mul takes 3-4 times cycles of add these days, so you gonna get max 12.5% speed up (or zero, if it's actually 3 times) for the code which probably takes less than 20% of execution time (memory access will be the bottleneck, not number crunching)
No need for that young fella 🧐
JAVA SOLUTION
100% TEST CASES ✅
COMPLEXITY IN 0(N) TIME
but we have to return int value not string, so how we can do that
''' static BigInteger fibonacciModified(int t1, int t2, int n) { BigInteger[] arr = new BigInteger[n]; BigInteger tOne = new BigInteger(Integer.toString(t1)); BigInteger tTwo = new BigInteger(Integer.toString(t2)); arr[0] = tOne; arr[1] = tTwo; for(int i = 2; i < n; i++){ BigInteger iMinus1BigInteger = arr[i - 1]; BigInteger iMinus2BigInteger = arr[i - 2]; BigInteger powered = iMinus1BigInteger.pow(2); BigInteger poweredAndSum = powered.add(iMinus2BigInteger); arr[i] = poweredAndSum; }''' BigInteger result = arr[n-1];
what is the function that is to be used in c to handle such big integer like this 84266613096281243382112? help me in doing this
There is not! And this is the challenge. You will need to cut the number in pieces to work with it.
Same concern. Luckily I'm on Python.
Totally agree. This really shouldn't be categorized as a dynamic programming problem. Without having to worry about big numbers the solution is trival.
For people using C#, just use System.Numerics.BigInteger.
Tried doing it with strings. But, it TLE'd on 4 test cases! T_T