Write a program to find all Armstrong numbers from 1 to N.
Example 1:
Input :n=1000
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]
Approach:
Java
import java.util.ArrayList;import java.util.List;public class ArmstrongNumber1ToN {public static void main(String[] args) {int num = 1000;List<Integer> allArm = checkArmstrong1ToN(num);System.out.println("All Armstrong are " + allArm);}// Method for check all armstrong numberprivate static List<Integer> checkArmstrong1ToN(int num) {// create list for hold numberList<Integer> allArm = new ArrayList<Integer>();// iterate from 1 to numfor (int i = 1; i <= num; i++) {// check current number is armstrongif (checkArmstrong(i))allArm.add(i);}return allArm;}// method used for check armstrong numberprivate 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 used for check armstrong numberbool checkArmstrong(int num) {int arm = 0;int n = num;// Length of given numberint length = (int)log10(num) + 1;while (n > 0) {int mod = n % 10;arm +=pow(mod, length);n = n / 10;}if (num == arm)return true;return false;}//function to find all armstrong number//till given numbervector<int> checkArmstrong1ToN(int num) {//vector to hold the armstrong//numbervector<int> allArm ;// iterate from 1 to numfor (int i = 1; i <= num; i++) {// check current number is armstrongif (checkArmstrong(i))allArm.push_back(i);}return allArm;}int main(){int num = 1000;vector<int> allArm = checkArmstrong1ToN(num);cout<<"All Armstrong are ";for(int i=0;i<allArm.size();i++)cout<<allArm[i]<<" ";;return 0;}
No comments:
Post a Comment