Last active
April 25, 2017 13:59
-
-
Save LuxXx/468685824ccb43ac737b2994b8184c2f to your computer and use it in GitHub Desktop.
Project Euler - Problem 92
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package euler; | |
public class ChainMember { | |
private int n; | |
// we use a -1 as n to indicate that this is a 89 to differ them from 0 or 1 | |
private static final ChainMember EIGHTYNINE = new ChainMember(-1); | |
public ChainMember(int n) { | |
this.n = n; | |
} | |
private static int next(int n) { | |
String s = String.valueOf(n); | |
int sum = 0; | |
for (int i = 0; i < s.length(); i++) { | |
int d = s.charAt(i) - 48; | |
sum += d*d; | |
} | |
return sum; | |
} | |
public ChainMember next() { | |
if (n == 0) return null; | |
if (n == 1) return null; | |
if (n == 89) return EIGHTYNINE; | |
ChainMember next = new ChainMember(next(n)); | |
return next; | |
} | |
public boolean is89() { | |
return n == -1; | |
} | |
@Override | |
public boolean equals(Object obj) { | |
if (!(obj instanceof ChainMember)) return false; | |
return (n == ((ChainMember) obj).n); | |
} | |
public static void main(String[] args) { | |
long s = System.currentTimeMillis(); | |
int eightyniners = 0; | |
for (int i = 0; i < 10_000_000; i++) { | |
ChainMember cm = new ChainMember(i); | |
while (cm != null) { | |
if (cm.is89()) { | |
eightyniners++; | |
break; | |
} | |
cm = cm.next(); | |
} | |
} | |
System.out.println(eightyniners); | |
System.out.println((System.currentTimeMillis() - s) / 1000 + "s"); | |
} | |
@Override | |
public String toString() { | |
return String.valueOf(n); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment