Skip to content

Instantly share code, notes, and snippets.

@M-ZubairAhmed
Created February 13, 2017 08:59
Show Gist options
  • Save M-ZubairAhmed/085eb326912531dda34b06002f977d6c to your computer and use it in GitHub Desktop.
Save M-ZubairAhmed/085eb326912531dda34b06002f977d6c to your computer and use it in GitHub Desktop.
The sum of each digit when raised to its position value equals the former number
/*
89 is a unique number and searching similar others
The number 89 is the first integer with more than one digit that fulfills the property partially introduced below:
example
89 = 8^1 + 9^2
135 = 1^1 + 3^2 + 5^3
The sum of each digit when raised to its position value equals the former number
A range is given and all those numbers with above property is collected.
*/
public class SumDigPower {
public static List<Long> sumDigPow(long a, long b){
List<Long> numberArList = new ArrayList<>(); //returning ArrayList of Long
while (a<=b){ //inbetween the range
String stringFromInt = new StringBuilder().append(a).toString(); //converting every number to string
int[] intArFromString = new int[stringFromInt.length()];
double sum = 0;
for (int i = 0; i < stringFromInt.length(); i++) {
intArFromString[i] = stringFromInt.charAt(i) - '0'; //getting into int array by substracting 0 ASCI code
sum = sum + Math.pow(intArFromString[i],i+1);} //math
int sumInt = (int) sum; //type casting to make it equal to long
if (a == sumInt){
numberArList.add(a);}
a++;} //increasing the input number
return numberArList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment