So, this is going to be a hard one to follow.. I believe it requires me to post all of my code in order to get the idea.. So if you have the time (or if you love me that much), I would appreciate it if you took a look at this.. Here's the original Problem 37. I have looked over my code several times and can't seem to discover my error. Well, here we go:
import java.util.*; public class prob37 { public static void main(String args[]){ int sum = 0; ArrayList<String> list = new ArrayList<String>(); for(int i = 1000000; i > 100; i--){ for(int a = 0; a < list.size(); a++){ if(list.get(a).contains("" + i)){ i--; } } if(allPrimeLeft(i) && allPrimeRight(i)){ System.out.println(i); list.add("" + i); sum+=i; } } System.out.println(sum); } public static boolean isPrime(int n){ if(n%2==0) return false; for(int i = 3; i < Math.sqrt(n)+1; i+=2){ if(n%i==0) return false; } return true; } public static boolean allPrimeLeft(int n){ if(!isPrime(n)) return false; String s = "" + n; for(int i = 0; i < s.length()-1;i++){ s = s.substring(1, s.length()); int temp = Integer.parseInt(s); if(!isPrime(temp)) return false; } return true; } public static boolean allPrimeRight(int n){ if(!isPrime(n)) return false; while(n > 0){ if(!isPrime(n)) return false; n/=10; } return true; } }
If you looked over this, and got to this point, YOURE AWESOME! Haha, but I'm going to keep looking it over as well... Please comment back if you have any question over my code or have a pointer for me to follow.
Output:
739397
73331
31193
19739
7331
3797
3137
1997
1373
719
317
179
173
131
113
882927 ---> This is the Sum I receive.
There are only supposed to be 11 numbers, but I return 15. Also the correct Sum is 748317. Maybe we can work this through the output.
Difference Between My Sum and The Actual Sum = 134610