I am trying to program a method that determines if a given number is an armstrong number. An armstrong number can be found by the steps below:
- Take base digits ie 456 => 4, 5, 6
- Power to the number of digits ie 456 has 3 digits, so pow = 3
- Power each base by the pow ie 4^3, 5^3, 6^3
- Total all sums ie 64 + 125 + 216 = 405
If sum equals original number, is armstrong ie 405 != 456, so not armstrong.
int armstrong(float number){ if(number < 1){ return 0; } else{ float *pointer = malloc(sizeof (float)), *temp; if(pointer == NULL){ printf("Error allocating memory: math::armstrong.\nReturn value 0."); return 0; } else{ int temp_boolean = 1, index = 0; float sum = 0, original_number = number; while(temp_boolean == 1){ if(number / 10 == 0){ temp_boolean = 0; } else{ temp = realloc(pointer, ((sizeof pointer / sizeof (float)) + 1) * sizeof (float)); pointer = temp; } pointer[index] = fmod(number, 10.0); //pointer[index] = number % 10; number /= 10; ++index; } int i; for(i = 0; i < index; ++i){ float temp_e = pointer[i]; sum += pow(temp_e, index); } free(pointer); if(sum == original_number){ return 1; } else{ return 0; } } }
}
My program returns 1 if given number is an armstrong number or 0 if it is not. Now, this works fine when i have the variables and params as an int, but i want to be able to recieve bigger numbers, which is why my code has variables in float. But for some reason, it is not giving any output. It compiles fine with gcc with the -Wall option, so i don't know what im doing wrong.
I'm using notepad++ to write my program, and gcc to compile.