input a,b output all armstrong numbers in [a,b] in 1s and 1<=a<=b<=10^7

Viewed 50

This is my code about c++ I do on IDE of my school and when i run the code on it.It have 10 test to run the program and it said just 8 test correct and 2 test is time limit exceeded because it allow the program run in 1 second so i want to ask are they another way to make my program run faster.I'm the beginer with stack overflow so i don't use to do this if there anything wrong pleas tell me thank you

#include <bits/stdc++.h>
#include <cmath>
using namespace std;
int main()
    long long a,b;
cin>>a>>b;
for(long long i=a;i<=b;i++){
    int digit=0;
    long long number=i,sum=0;
    while(number!=0){
        number=number/10;
        digit++;
    }
    number=i;
    while(number!=0){
        sum=sum+(pow((number%10),digit));
        number=number/10;
    }
    number=i;
    if(number==sum){
        cout<<number<<" ";
    }
}
}
1 Answers

Probably using logarithm in base 10, if you use logarithm in base 10 trunc plus 1 of a number you obtain the number of digits. And use a vector initialized with the pows of 0,1,2,...9 to digit potency instead reacalculate in every interation.

Related