Find the sum of all numbers below N which divide the sum of the factorial of their digits.
Note: 1,2,.....9 are included.
Note: 1,2,.....9 are included.
Example:
Input: 20 Output: 19 //i.e 19 1!+9!=1+362880 =362881 which is divisble by 19
Approach
Java
public class DigitFactorials {public static void main(String[] args) {int n = 20;int sum = 0;for (int i = 10; i <= n; i++) {if (isSumFact(i))sum += i;}System.out.println(sum);}// function to check if// sum of factorial is// divisible by the numberprivate static boolean isSumFact(int n) {int num = n;int sum = 0;while (n > 0) {sum += factorialR(n % 10);n = n / 10;}if (sum % num == 0)return true;return false;}// factorial methodprivate static int factorialR(int num) {if (num <= 1)return 1;return num * factorialR(num - 1);}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the factorial of//the given numberint fact(int n){if(n<=1)return 1;return n*fact(n-1);}//function to check if//sum of factorial is//divisible by the numberbool isSumFact(int n){int num=n;int sum=0;while(n>0){sum+=fact(n%10);n=n/10;}if(sum%num==0)return true;return false;}int main(){int n=20;int sum=0;for(int i=10;i<=n;i++){if(isSumFact(i))sum+=i;}cout<<sum<<"\n";return 0;}
No comments:
Post a Comment