Here is the problem link : https://www.hackerrank.com/challenges/down-to-zero-ii/problem
I used bottom up dp , but still getting stack overflow runtime error for input 1000000 . Can anyone help me , to point out where is wrong in my code :
code
Here is the problem link : https://www.hackerrank.com/challenges/down-to-zero-ii/problem
I used bottom up dp , but still getting stack overflow runtime error for input 1000000 . Can anyone help me , to point out where is wrong in my code :
# include < bits/stdc++. h >
using namespace std;
int n,q,i,j;
int dp[2000000];
int flag[2000000];
int recursion(int N) {
// cout<<N<<endl;
if(N==0)
return 0;
if(dp[N]!=-1)
return dp[N];
int x=recursion(N-1)+1;
int y=2147483647;
for(int i=2; i*i<=N; i++)
if(N%i==0)
y=min(y,recursion(N/i)+1);
dp[N]=min(x,y);
return dp[N];}
int main() {
memset(dp,-1,sizeof(dp));
scanf("%d",&q);
while(q--) {
scanf("%d",&n);
printf("%d\n",recursion(n));
}
return 0;}
| # | User | Rating |
|---|---|---|
| 1 | Benq | 3792 |
| 2 | VivaciousAubergine | 3647 |
| 3 | Kevin114514 | 3603 |
| 4 | jiangly | 3583 |
| 5 | turmax | 3559 |
| 6 | tourist | 3541 |
| 7 | strapple | 3515 |
| 8 | ksun48 | 3461 |
| 9 | dXqwq | 3436 |
| 10 | Otomachi_Una | 3413 |
| # | User | Contrib. |
|---|---|---|
| 1 | Qingyu | 157 |
| 2 | adamant | 153 |
| 3 | Um_nik | 147 |
| 4 | Proof_by_QED | 146 |
| 5 | Dominater069 | 145 |
| 6 | errorgorn | 142 |
| 7 | cry | 139 |
| 8 | YuukiS | 135 |
| 9 | TheScrasse | 134 |
| 10 | chromate00 | 133 |
| Name |
|---|



Is this problem impossible to solve with Bottom up DP ? I solved using top down dp , using queue .
for $$$N=0$$$ you return $$$n$$$? shouldn't this be $$$0$$$?
This is bottom up, gets accepted and its more or less in $$$O(n\sqrt{n})$$$:
This is $$$O(n\cdot log(n))$$$, as it can be written as $$$\sum_{i=1}^n\frac{n}{i} \simeq n \cdot ln(n) = O(n \cdot log(n))$$$
oh yes you are right.
Yeah, it should be 0. But still it overflow on 1000000
and you probably want to initialize $$$dp$$$ with $$$0$$$ and not $$$-1$$$ ?