I have been working on this for a while, and I can't quite figure out why my code is printing 2091059712, which is apparently incorrect. For those who don't know, the challenge is to find the 13 adjacent digits in that long string that multiply to equal the highest number product.
package Project_Euler;
public class problem8 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//These 2 variables are chosen by the user. For the purpose of Euler Challenge, I have these values set as they are.
int numToTest = 13;
String num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949" +
"49545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111" +
"21722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121" +
"88399879790879227492190169972088809377665727333001053367881220235421809751254540594752243525849077116705560136048395864467" +
"06324415722155397536978179778461740649551492908625693219784686224828397224137565705605749026140797296865241453510047482166" +
"37048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456" +
"82848912883142607690042242190226710556263211111093705442175069416589604080719840385096245544436298123098787992724428490918" +
"88458015616609791913387549920052406368991256071760605886116467109405077541002256983155200055935729725716362695618826704282" +
"52483600823257530420752963450";
//setting basic variables
int test = numToTest - 1;
int length = num.length();
int[] array = new int[length];
int result = 0;
int[] testing = new int[numToTest];
int product = 1;
//Setting the array to have values equal to the corresponding values in the number above.
for(int n = 0; n <= length - 1; n++){
//The minus 48 is because the code adds 48 to the value for some reason
array[n] = Integer.valueOf(num.charAt(n) - 48);
}
//Multiplies 13 digits together and tests which set comes out with the highest product
for(int n = 0; n < length; n++){
//assures that it only checks when there are enough digits to multiply together
if(n + test < length){
product = 1;
//goes through the digits, multiplying them by the next one.
for(int check = 0; check <= test; check++){
product *= array[n + check];
testing[check] = array[n + check];
}
//finds the greatest product
if(product > result){
result = product;
}
}
}
//Prints the greatest product
System.out.println(result);
}
}
I have checked that the numbers involved are correct, and same with each code statement.