Extended Divisibility

 Extended Divisibility 

PROBLEM STATEMENT :

The program must accept two integer values N and K as the input. The program must form a list of integers. The first value in the list is N. If N is divisible by K, then the integer value N/K must be added to the list for K times. Then the program must repeat the process for all the newly added integers in the list. Finally, the program must print the integer values in the list as the output. 

Boundary Condition(s): 

2 <= N <= 10^5 

2 <= K <= 100 

Input Format: 

The first line contains N and K separated by a space. 

Output Format: 

The first line contains the integer values in the list separated by a space. 

Example Input/Output 1: 
Input: () 
4 2 
Output: 4 2 2 1 1 1 1

Explanation: 

Here N=4 and K=2 

Initially, the list contains 4. 

N is divisible by K, so 2 (4/2) is added to the list K times. 

The newly added values are 2 2 and divisible by K=2. 

Hence 2/2 = 1 is added K times for each 2. 

Hence 1 is added 4 times. 

The newly added values are 1 1 1 1 and they are not divisible by K=2. 

Hence we stop. Now the values in the list are 4 2 2 1 1 1 1 and printed as the output. 

Example Input/Output 2: 
Input: () 
10 5 
Output: 10 2 2 2 2 2

Example Input/Output 3: 
Input: () 
7 5 
Output: 7



SOLUTION :

C (Programming Language)


      

#include<stdio.h> #include<stdlib.h> int main() { int N,K; scanf("%d %d",&N,&K); int a[N*K]; a[0]=N; int size=1; for(int i=0;;i++) { if(a[i]%K==0) { for(int j=0;j<K;j++) { a[size++] = a[i]/K; } } else { break; } } for(int i=0;i<size;i++) { printf("%d ",a[i]); } }



C++ (CPP)

       

#include <bits/stdc++.h> using namespace std; int main(int argc, char** argv) { int n , k ; cin >> n >> k; vector<int> vec = {n}; int ind = 0 ; while(ind < vec.size()) { if(vec[ind]%k==0) { for(int i = 0 ; i<k ; i++) vec.push_back(vec[ind]/k); } ind++; } for(int i : vec) cout << i << " "; }



JAVA

       

import java.util.*; public class Hello { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int N=sc.nextInt(),K=sc.nextInt(); ArrayList<Integer> numList=new ArrayList<>(); int index=0; numList.add(N); while(numList.get(index)%K==0){ for(int ctr=1;ctr<=K;ctr++){ numList.add(numList.get(index)/K); } index++; } for(int num:numList){ System.out.print(num+" "); } } }



PYTHON

       

n,k=map(int,input().split()) l=[n];i=0 while i<len(l) and l[i]%k==0: l.extend([l[i]//k]*k) i+=1 print(*l)



Never Stop Learning !!


Comments

Popular posts from this blog

DP (1) - Count number of ways to cover a distance

Zero Insert After K Times One

Left Number Twice Right