To find nth fibonacci number using memoization I found one code which uses map
in c++.
I have tried to convert this code in java but it fails .
code in c++:
#include <bits/stdc++.h>
typedef long long int ll;
map<ll, ll> mp;
ll M = 1000000007;
long long fibonacci(long long n) {
if (mp.count(n))return mp[n];
long long k=n/2;
if (n%2==0) {
return mp[n] = fibonacci(k)*(fibonacci(k+1)+fibonacci(k-1)) % M;
} else {
return mp[n] = (fibonacci(k+1)*fibonacci(k+1) + fibonacci(k)*fibonacci(k)) % M;
}
}
int main()
{
mp[0]=mp[1]=1;
ll t;
scanf("%lld",&t);
printf("%lld\n",fibonacci(t));
}
I have tried same code in java using HashMap
.
code in java:
static HashMap<Long,Long> hm=new HashMap<Long,Long>();
static long f(long n) {
if (hm.containsKey(n)) return hm.get(n);
long k=n/2;
if (n%2==0) {
return hm.put(n,f(k)*(f(k+1)+f(k-1)) % M);
} else {
return hm.put(n, (f(k+1)*f(k+1) + f(k)*f(k)) % M);
}
}
public static void main(String[] args) throws IOException {
hm.put(1L,1L);
hm.put(0L,1L);
long b=f(2L);
}
but this code in java gives StackOverflowError
.
I have tried this code using LinkedHashMap
and TreeMap
in java both gives same error.
Which class I have to use which works same as map
in c++?
Please someone explain how map
work in c++.
EDIT
look at the output of code in java
and c++
c++: c++ code
java: java code