Find all digits of given number N that are factors of N
Last Updated :
27 Jan, 2022
Given a number N, the task is to print the digits of N which divide N.
Example:
Input: N = 234
Output: 2 3
Input: N = 555
Output: 5
Approach: The idea is to iterate over all the digits of N and check whether that digit divides N or not. Follow the steps below to solve the problem:
- Initialize the variables tem as N.
- Traverse over the while loop till tem not equals to 0 and perform the following tasks:
- Initialize the variable rem as tem%10.
- If n%rem equals 0 then print rem as the answer.
- Divide tem by 10.
Below is the implementation of the above approach.
C++
#include <iostream>
using namespace std;
void printDigitFactors( int n)
{
int tem = n;
int rem;
while (tem != 0) {
int rem = tem % 10;
if (n % rem == 0) {
cout << rem << ' ' ;
}
tem /= 10;
}
}
int main()
{
int N = 234;
printDigitFactors(N);
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static void printDigitFactors( int n)
{
int tem = n;
int rem;
while (tem != 0 ) {
rem = tem % 10 ;
if (n % rem == 0 ) {
System.out.print(rem + " " );
}
tem /= 10 ;
}
}
public static void main (String[] args) {
int N = 234 ;
printDigitFactors(N);
}
}
|
Python3
def printDigitFactors(n):
tem = n;
rem = None
while (tem ! = 0 ):
rem = tem % 10 ;
if (n % rem = = 0 ):
print (rem, end = ' ' );
tem = tem / / 10
N = 234 ;
printDigitFactors(N);
|
C#
using System;
class GFG
{
static void printDigitFactors( int n)
{
int tem = n;
int rem = 0;
while (tem != 0) {
rem = tem % 10;
if (n % rem == 0) {
Console.Write(rem + " " );
}
tem /= 10;
}
}
public static void Main()
{
int N = 234;
printDigitFactors(N);
}
}
|
Javascript
<script>
function printDigitFactors(n) {
let tem = n;
let rem;
while (tem != 0) {
let rem = tem % 10;
if (n % rem == 0) {
document.write(rem + ' ' );
}
tem = Math.floor(tem / 10);
}
}
let N = 234;
printDigitFactors(N);
</script>
|
Time Complexity: O(K), where K is the number of digits in N
Auxiliary Space: O(1).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...