Given a positive integer N. The task is to find the sum and product of digits of the number which evenly divides the number n.
Examples:
Input: N = 12
Output: Sum = 3, product = 2
1 and 2 divide 12. So, their sum is 3 and product is 2.
Input: N = 1012
Output: Sum = 4, product = 2
1, 1 and 2 divide 1012.
Approach: The idea is to find each digit of the number n by modulus 10 and then check whether it divides n or not. Accordingly, add it to the sum and multiply it with the product. Notice that the digit can be 0, so take care of that case.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countDigit( int n)
{
int temp = n, sum = 0, product = 1;
while (temp != 0) {
int d = temp % 10;
temp /= 10;
if (d > 0 && n % d == 0) {
sum += d;
product *= d;
}
}
cout << "Sum = " << sum;
cout << "\nProduct = " << product;
}
int main()
{
int n = 1012;
countDigit(n);
return 0;
}
|
Java
import java.lang.*;
import java.util.*;
class GFG
{
static void countDigit( int n)
{
int temp = n, sum = 0 , product = 1 ;
while (temp != 0 )
{
int d = temp % 10 ;
temp /= 10 ;
if (d > 0 && n % d == 0 )
{
sum += d;
product *= d;
}
}
System.out.print( "Sum = " + sum);
System.out.print( "\nProduct = " + product);
}
public static void main(String args[])
{
int n = 1012 ;
countDigit(n);
}
}
|
Python3
def countDigit(n):
temp = n
sum = 0
product = 1
while (temp ! = 0 ):
d = temp % 10
temp / / = 10
if (d > 0 and n % d = = 0 ):
sum + = d
product * = d
print ( "Sum =" , sum )
print ( "Product =" , product)
if __name__ = = '__main__' :
n = 1012
countDigit(n)
|
C#
using System;
class GFG
{
static void countDigit( int n)
{
int temp = n, sum = 0, product = 1;
while (temp != 0)
{
int d = temp % 10;
temp /= 10;
if (d > 0 && n % d == 0)
{
sum += d;
product *= d;
}
}
Console.Write( "Sum = " + sum);
Console.Write( "\nProduct = " + product);
}
public static void Main()
{
int n = 1012;
countDigit(n);
}
}
|
PHP
<?php
function countDigit( $n )
{
$temp = $n ;
$sum = 0;
$product = 1;
while ( $temp != 0) {
$d = $temp % 10;
$temp =(int)( $temp /10);
if ( $d > 0 && $n % $d == 0) {
$sum += $d ;
$product *= $d ;
}
}
echo "Sum = " . $sum ;
echo "\nProduct = " . $product ;
}
$n = 1012;
countDigit( $n );
?>
|
Javascript
<script>
function countDigit(n)
{
let temp = n;
let sum = 0;
let product = 1;
while (temp != 0) {
let d = temp % 10;
temp =parseInt(temp/10);
if (d > 0 && n % d == 0) {
sum += d;
product *= d;
}
}
document.write( "Sum = " +sum);
document.write( "<br>Product = " +product);
}
let n = 1012;
countDigit(n);
</script>
|
Output:
Sum = 4
Product = 2
Time Complexity: O(log10n), Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!