Write a program to check Armstrong number.
Armstrong Number: An Armstrong number or a plus perfect number in a given base is a number that is the sum of its own digits each raised to the power of the number of digits.
Example 1:
Input:num=153
Output:true Explanation: 1^3+5^3+3^3=153
Example 2:
Input:num=15
Output:false Explanation: 1^2+5^2!=15
Approach
Java
public class ArmstrongNumber {public static void main(String[] args) {int num = 153;if (checkArmstrong(num)) {System.out.println(num + " is Armstrong");} else {System.out.println(num + " is not Armstrong");}}private static boolean checkArmstrong(int num) {int arm = 0;int n = num;// Length of given numberint length = (int) Math.log10(num) + 1;while (n > 0) {int mod = n % 10;arm += Math.pow(mod, length);n = n / 10;}if (num == arm)return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to check given number is//armstrong or notbool isArmstrong(int num){int n=num;//length of numberint length=log10(num)+1;int arm=0;while(n>0){int mod=n%10;arm=arm+pow(mod,length);n=n/10;}if(arm==num)return true;elsereturn false;}int main(){int num=153;if(isArmstrong(num))cout<<"Number is Armstrong\n";elsecout<<"Number is not Armstrong\n";}
No comments:
Post a Comment