Find N digits number which is divisible by D
Last Updated :
20 Sep, 2022
Given and . The task is to find an N digit number that is divisible by D ( 2 <= D <= 10). If it is not possible, then print Impossible.
Examples:
Input : N = 2 and D = 2
Output : 20
Input : N = 1 and D = 10
Output : Impossible
Approach: There are two conditions, D=10 and D not equal to 10. If D = 10 and N = 1 then the only answer is not possible and in all other conditions, the answer will be possible.
1. If D is 10,
Print 1 followed by n-1 times zero.
2. If D is not 10
Print D followed by n-1 times zero
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string findNumber( int n, int d)
{
string ans = "" ;
if (d != 10) {
ans += to_string(d);
for ( int i = 1; i < n; i++)
ans += '0' ;
}
else {
if (n == 1)
ans += "Impossible" ;
else {
ans += '1' ;
for ( int i = 1; i < n; i++)
ans += '0' ;
}
}
return ans;
}
int main()
{
int n = 12, d = 3;
cout << findNumber(n, d);
return 0;
}
|
Java
import java.io.*;
class GFG {
static String findNumber( int n, int d)
{
String ans = "" ;
if (d != 10 ) {
ans += Integer.toString(d);
for ( int i = 1 ; i < n; i++)
ans += '0' ;
}
else {
if (n == 1 )
ans += "Impossible" ;
else {
ans += '1' ;
for ( int i = 1 ; i < n; i++)
ans += '0' ;
}
}
return ans;
}
public static void main (String[] args) {
int n = 12 , d = 3 ;
System.out.println(findNumber(n, d));
}
}
|
Python 3
def findNumber(n, d):
ans = ""
if (d ! = 10 ) :
ans + = str (d)
for i in range ( 1 ,n):
ans + = '0'
else :
if (n = = 1 ):
ans + = "Impossible"
else :
ans + = '1'
for i in range ( 1 ,n):
ans + = '0'
return ans
if __name__ = = "__main__" :
n = 12
d = 3
print (findNumber(n, d))
|
C#
using System;
class GFG {
static string findNumber( int n, int d)
{
string ans = "" ;
if (d != 10) {
ans += d.ToString();
for ( int i = 1; i < n; i++)
ans += '0' ;
}
else {
if (n == 1)
ans += "Impossible" ;
else {
ans += '1' ;
for ( int i = 1; i < n; i++)
ans += '0' ;
}
}
return ans;
}
public static void Main ()
{
int n = 12, d = 3;
Console.WriteLine(findNumber(n, d));
}
}
|
PHP
<?php
function findNumber( $n , $d )
{
$ans = "" ;
if ( $d != 10)
{
$ans .= strval ( $d );
for ( $i = 1; $i < $n ; $i ++)
$ans .= '0' ;
}
else
{
if (n == 1)
$ans .= "Impossible" ;
else
$ans .= '1' ;
for ( $i = 1; $i < $n ; $i ++)
$ans .= '0' ;
}
return $ans ;
}
$n = 12;
$d = 3;
print (findNumber( $n , $d ));
|
Javascript
<script>
function findNumber(n,d)
{
let ans = "" ;
if (d != 10) {
ans += (d).toString();
for (let i = 1; i < n; i++)
ans += '0' ;
}
else {
if (n == 1)
ans += "Impossible" ;
else {
ans += '1' ;
for (let i = 1; i < n; i++)
ans += '0' ;
}
}
return ans;
}
let n = 12, d = 3;
document.write(findNumber(n, d));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...