Down to zero ii hackerrank solution

Down to Zero II, is a HackerRank problem from Queues subdomain. In this post we will see how we can solve this challenge in Python

Problem Description

You are given queries. Each query consists of a single number . You can perform any of the operations on in each move: 1: If we take 2 integers and where , , then we can change

2: Decrease the value of by .

Determine the minimum number of moves required to reduce the value of to .

Input F ....

You can find the full details of the problem Down to Zero II at HackerRank

Solution: Please check the down-to-zero-ii.py snippet for the solution.

This solution originally posted at: Github by @srgnk

In C ++ : #include <bits/stdc++.h> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int test; cin >> test; while (test--){ int n ; cin >> n ; int steps = 0; if (n==0){ cout << 0 << endl; continue; } if (n==1){ cout << 1 << endl; continue; } vector<int> dist(n+1,0); queue<int> q; q.push(n) ; dist[n] = 1 ; while (1){ int element = q.front(); q.pop(); if(element == 2){ cout << dist[2] + 1 << endl; break ; } if (dist[element-1] == 0 ){ dist [element-1] = dist[element]+1; q.push(element-1); } for (int i=2; i*i<=element; i++){ if (element%i == 0){ int maxfrac = element/i; if (dist[maxfrac] == 0) dist [maxfrac] = dist[element] + 1, q.push(maxfrac); } } } } return 0; } In Java : import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { private static int MAXSZ = (int)(1E6+1); private static int[] dp; private static int minimumMove(int n) { if(n == 0) return 0; if(dp[n] != -1) return dp[n]; int minMove = Integer.MAX_VALUE; int sq = (int) Math.sqrt(n); for(int i = 2; i <= sq; i++) { if(n % i == 0) { minMove = Math.min(minMove, 1+minimumMove(n/i)); } } minMove = Math.min(minMove, 1+ minimumMove(n-1)); return (dp[n] = minMove); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); dp = new int[MAXSZ]; Arrays.fill(dp, -1); dp[0] = 0; dp[1] = 1; dp[2] = 2; int Q = sc.nextInt(); for(int q = 1; q <= Q; q++) { int n = sc.nextInt(); System.out.println(minimumMove(n)); } } } In C : #include <stdio.h> #include <stdio.h> #include <string.h> unsigned long long min(unsigned long long x, unsigned long long y); unsigned long long ans[1000001]; int main(){ int Q,N,i,j; memset(ans,-1,sizeof(ans)); ans[0]=0; for(i=0;i<1000000;i++){ ans[i+1]=min(ans[i+1],ans[i]+1); for(j=2;j<=i && i*(unsigned long long)j<1000001;j++) ans[i*j]=min(ans[i*j],ans[i]+1); } scanf("%d",&Q); while(Q--){ scanf("%d",&N); printf("%llu\n",ans[N]); } return 0; } unsigned long long min(unsigned long long x, unsigned long long y){ return (x>y)?y:x; } In Python3 : import math import time start = time.time() def Sol( N ): if N == 0: return 0 Q = [ (N,0) ] setQ = [ 0 ] * N while Q: N, steps = Q.pop(0) if N == 1: return steps+1 div = int(math.sqrt( N )) while div > 1: if N % div == 0 and not setQ[N // div]: Q.append( (N // div, steps+1) ) setQ[ N // div ] = 1 div -= 1 if not setQ[N-1]: Q.append( (N-1, steps+1) ) setQ[ N-1 ] = 1 Q = int(input()) for _ in range(Q): N = int(input()) print(Sol(N))

In this HackerRank Down to Zero II problem, we have given Q queries. each query consists of a single number N. we need to determine the minimum number of moves required to reduce the value of N to 0 after performing operations on N.

Down to zero ii hackerrank solution

Problem solution in Python programming.

import collections lim = 10**6+1 dist = [0]*lim active = collections.deque() active.append(0) while active: n = active.popleft() d = dist[n]+1 x = n + 1 if x < lim and dist[x] == 0: dist[x] = d active.append(x) for m in range(2,n+1): x = m * n if x >= lim: break if dist[x] == 0: dist[x] = d active.append(x) Q = int(input()) for q in range(Q): N = int(input()) print(dist[N])

Problem solution in Java Programming.

import java.io.*; import java.util.*; public class Solution { static int[] moves = new int[1000001]; public static void main(String[] args) { for (int i = 1; i <= 1000000; ++i) { int least = moves[i - 1]; for (int j = 2; j * j <= i; ++j) { if (i % j == 0) { least = Math.min(least, moves[i / j]); } } moves[i] = ++least; } Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { System.out.println(moves[in.nextInt()]); } } }

Problem solution in C++ programming.

#include <map> #include <cmath> #include <queue> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define NSIZE 1000000 vector< vector<int> > ar(NSIZE+1); bool primes[NSIZE+1]; int cache[NSIZE], dcache[NSIZE]; void gen_primes() { for (int i = 2; i <= NSIZE; i++) { } for (int i = 1; i <= NSIZE; i++) { bool prime = true; for (int j = 2; j*j<= i; j++) { if (i % j == 0) { prime = false; break; } } primes[i] = prime; } } void get_a(int n) { if (primes[n]) return; if (dcache[n] != -1) return; else dcache[n] = 1; for (int i = 2; i*i <= n; i++) { if (n % i == 0) { int v = n / i; if (v == 1 || i == 1) continue; v = v > i ? v : i; ar[n].push_back(v); } } } int w[NSIZE]; void fill_cache(int steps, int number, int start) { int indx = start; int st = 1; if (cache[start] != -1) st = cache[start] + 1; while(1) { int pos = w[indx]; cache[pos] = st++; indx = pos; if (st == steps + 1) break; } } int *q; int qpos = 0; int qend = 0; int steps = 0; int cal_steps(int v) { for (int i = 0; i <= v; i++) w[i] = -1; qpos = 0; qend = 0; steps = 0; q[qend++] = v; q[qend++] = -1; while(1) { int val = q[qpos++]; if (val == -1) { steps ++; q[qend++] = -1; val = q[qpos++]; } if (val == 0) { return steps; } get_a(val); for (int i = 0; i < ar[val].size(); i++) { if (w[ar[val][i]] == -1) w[ar[val][i]] = val; int tmp_val = ar[val][i]; q[qend++] = tmp_val; } val -= 1; q[qend++] = val; } return -1; } int main() { std::ios_base::sync_with_stdio (false); q = new int[NSIZE * 19]; int n, v; cin >> n; int max = n; for (int i = 0; i < NSIZE; i++) { cache[i] = -1; dcache[i] = -1; } gen_primes(); while(n--) { cin >> v; if (v == 0) { cout << "0" << endl; continue; } cout << cal_steps(v) << endl; } return 0; }

Problem solution in C programming.

#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> #define N_MAX 1000001 int solns[N_MAX]; void initialize_solns() { for (int i = 0; i < N_MAX; i++) { solns[i] = 0; } solns[1] = 1; solns[2] = 2; solns[3] = 3; solns[4] = 3; // Actually solve for (int i = 1; i < N_MAX; i++) { if (!solns[i] || solns[i-1] + 1 < solns[i]) { solns[i] = solns[i-1] + 1; } for (int j = 1; j <= i && j * i < N_MAX; j++) { if (!solns[j*i] || solns[i] + 1 < solns[j*i]) { solns[j*i] = solns[i] + 1; } } } } int main() { initialize_solns(); int Q; scanf("%i", &Q); for(int a0 = 0; a0 < Q; a0++){ int N; scanf("%i", &N); printf("%d\n", solns[N]); } return 0; }

Problem solution in JavaScript programming.

'use strict'; const fs = require('fs'); process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(str => str.trim()); main(); }); function readLine() { return inputString[currentLine++]; } var minCostMap = {0:0,1:1,2:2,3:3}; function getReductions(n){ var sqrt = Math.floor(Math.sqrt(n)); var reductions = [n-1]; var r = 2; while(r<=sqrt){ if(n%r===0){ reductions.push(n/r); } r++; } //console.log(reductions); return reductions; } function min(reductions){ var minCost = Math.min();//infinity //console.log('reductions lenght: ',reductions.length); for(var i=reductions.length-1; i>=0; i--){ var c = downToZero(reductions[i]); //console.log('c: ',c,' n:',reductions[i]); if(c<minCost){ minCost=c; } } return minCost; } var minCostArray = [0,1,2,3]; function getMinCost(n){ var reductions = getReductions(n); return min(reductions)+1; } function downToZero(n){ var lastRecordedCost = minCostArray.length-1; if(n<=lastRecordedCost){ return minCostArray[n]; } while(n>lastRecordedCost){ var nextCost = getMinCost(++lastRecordedCost); minCostArray.push(nextCost); } //console.log('minCostArray.lenght ',minCostArray.length); //console.log('lastRecordedCost ',lastRecordedCost); //console.log(minCostArray); return minCostArray[lastRecordedCost]; } /* * Complete the downToZero function below. */ function downToZero2(n) { /* * Write your code here. */ if(minCostMap.hasOwnProperty(n)){ return minCostMap[n]; }else{ var reductions = getReductions(n); var minCost = min(reductions) + 1; minCostMap[n] = minCost; return minCost; } } function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const q = parseInt(readLine(), 10); for (let qItr = 0; qItr < q; qItr++) { const n = parseInt(readLine(), 10); let result = downToZero(n); ws.write(result + "\n"); } ws.end(); }