Write a program to Check the strong number.
Strong Number: A number is said to be strong if the sum of the factorial of each digit of the number is the same as the number
Example 1:
Input: num = 145
Output: Number is strong
Example 2:
Input: num = 321
Output: Not a strong number
Approach
Java
public class StrongNumber {public static void main(String[] args) {int num = 145;if (isStrong(num))System.out.println("Number is strong ");elseSystem.out.println("Not a strong number ");}private static boolean isStrong(int num) {int sum = 0;int n = num;while (n > 0) {sum += factorialR(n % 10);n /= 10;}if (sum == num)return true;return false;}private static int factorialR(int num) {if (num == 1 || num == 0)return 1;return num * factorialR(num - 1);}}
C++
#include <bits/stdc++.h>using namespace std;int fact(int n){if(n==1||n==0)return 1;return n*fact(n-1);}//function to check for//strong numberbool isStrong(int num){int temp=num;int sum=0;while(num>0){sum+=fact(num%10);num=num/10;}if(temp==sum)return true;return false;}int main(){int num=145;if(isStrong(num))cout<<"Number is strong ";elsecout<<"Not a strong number ";return 0;}
C
#include <stdio.h>#include <stdbool.h>int fact(int n){if (n == 1 || n == 0)return 1;return n * fact(n - 1);}//function to check for//strong numberbool isStrong(int num){int temp = num;int sum = 0;while (num > 0){sum += fact(num % 10);num = num / 10;}if (temp == sum)return true;return false;}int main(){int num = 145;if (isStrong(num)){printf("Number is strong ");}else{printf("Not a strong number ");}return 0;}
No comments:
Post a Comment