Currently I am trying to build a program that prints all armstrongnumbers till a certain number. I am getting some odd error when trying to run this. It says bufferoverflow.
The part causing it seems to be in main(). Thanks for any help.
#include <stdio.h>
#define MAXIMUM 1000000
int ipow(int x, int power){
int z,t;
t = 0;
z = x;
for (t = 0; t < (power - 1); t++) {
z = z * x; }
return z;
}
int getLength(int x) {
int a;
a = 1;
for (a=1;1;a++) { if (x < ipow(10,a) && x >= ipow(10,(a-1))) return a; }
}
int getExpSum(int x) {
int summe,r,s,t;
int digit[8]={0,0,0,0,0,0,0,0};
summe=0;
s = getLength(x);
t = x;
r = 1;
for (s=getLength(x);s!=0;s--){
digit[s] = t % 10;
t = t / 10;
}
for(r=1;r<(getLength(x)+1);r++)
{
summe = summe + ipow(digit[r],getLength(x));
}
return summe;
}
int Armstrong (int x) {
if (getExpSum(x)==x) {
printf("%d ist eine Armstrongzahl\n", x);
return 1;
}
return 0;
}
void main(){
int z;
z = 0;
for (z=0;z<MAXIMUM;z++){
Armstrong(z+1);
}
}
There is a problem in your “getLength” Function (actually ipow)
pass getLength(1) and you get result as 13 because
ipow(10, 1) and ipow(10, 0) returns 10 so the “getLength” condition fails and it goes for next iteration and goes on.. until the ipow returns a negative number thats 10^13 because of the integer size.
And inside getExpSum the array digit is of size 8 and it tries to acces the 13th element of it. Hence it crashes
Add the condition to the ipow function
After adding this condition I get the correct result.
BTW the solution can be improved.