Hello. I have a problem with the time of my code. I have a project to find numbers from 0 to 99999999 that have a certain property( Armstrong numbers)
e.g 1634= 1^4 + 6^4 + 3^4 + 4^4. I found a way to do this but my for loop has to go though so many numbers resulting my program stoping after 15 seconds. Is there anything i can do to reduce the time? Thanks in advance!
int N;
int m,a[10];
int main(){
cin>>N;
for(m=0;m<99999999;m++){
int num=m;
a[1]=num/10000000;
int x=num%10000000;
a[2]=x/1000000;
int y=x%1000000;
a[3]=y/100000;
int z=y%100000;
a[4]=z/10000;
int w=z%10000;
a[5]=w/1000;
int q=w%1000;
a[6]=q/100;
int c=q%100;
a[7]=c/10;
a[8]=c%10;
if(num==pow(a[1],N)+pow(a[2],N)+pow(a[3],N)+pow(a[4],N)+pow(a[5],N)+pow(a[6],N)+pow(a[7],N)+pow(a[8],N)){
//something
}
}
}
pow is slow for integers. if you need a pow for something (use a lookup table as said for any constants) write an efficient int power routine instead.
also, try a web search on an efficient algorithm to find the numbers. Brute force is rarely the best way. It looks like the sum of the digits in base 10 cubed == original number is the rule.
so you need all the digits cubed, for starters:
int d3[10] = {0,1,8,27, … etc};
blasted web. I see 2 definitions... one says cubed, and one says N where n = # of digits in the number. The cubed pages only has 3 digit examples. I am not motivated enough to unravel it, since I don't see any use for the numbers, but as said check your definition and see if you can find an efficient way to generate or detect them.