Code for Project Euler #8 not Working - java

I have spent a couple of hours struggling with this problem and I just can't figure out why it doesn't work. Basically, the question is to find the thirteen consecutive digits that have the greatest sum. If I modify it to look for four digits or five digits, it gets the correct answer, but when it looks for thirteen I get 2091059712, which is not correct. I am pretty new to coding, and am completely at a loss for what could be wrong.
// this is the 1000 digit number
String big = "73167176531330624919225119674426574742355349194934" +
"96983520312774506326239578318016984801869478851843"+
"85861560789112949495459501737958331952853208805511"+
"12540698747158523863050715693290963295227443043557"+
"66896648950445244523161731856403098711121722383113"+
"62229893423380308135336276614282806444486645238749"+
"30358907296290491560440772390713810515859307960866"+
"70172427121883998797908792274921901699720888093776"+
"65727333001053367881220235421809751254540594752243"+
"52584907711670556013604839586446706324415722155397"+
"53697817977846174064955149290862569321978468622482"+
"83972241375657056057490261407972968652414535100474"+
"82166370484403199890008895243450658541227588666881"+
"16427171479924442928230863465674813919123162824586"+
"17866458359124566529476545682848912883142607690042"+
"24219022671055626321111109370544217506941658960408"+
"07198403850962455444362981230987879927244284909188"+
"84580156166097919133875499200524063689912560717606"+
"05886116467109405077541002256983155200055935729725"+
"71636269561882670428252483600823257530420752963450";
ArrayList<Integer> nums = new ArrayList<Integer>();
int counter = 0;
for (counter = 0; counter<988; counter++) {
String str = big.substring (counter,counter+13);
// creates a substring thirteen digits long
Integer product = 1;
for (int o=0; o<13; o++) {
String num = Character.toString(str.charAt(o));
Integer numb = Integer.parseInt(num);
// Turns each digit into an integer and then multiplies them together
product = product*numb;
}
nums.add(product);
}
//finds biggest number
int bignum = 0;
for (Integer num : nums) {
if (num > bignum) {
bignum = num;
}
}
Any help would be greatly appreciated. Thanks.

Change all your Integers to Longs, your only problem is integer storage.

You need to change your numb and bignum to Longs instead of Ints, if that donsen't work then you can change them to BigIntegers.

Related

Cant find the percentage - JAVA

so I have this problem where finding the percentage doesn't work and I really don't know why,so my assignment is to find the number of candidates for election and the number of electors and at the end it should show the percentage of the votes example if there are 3 candidates and 6 electors and 1st candidate gets 3 votes,2nd gets 2 votes, and the 3rd gets 1 vote, it should show : 50.00%,33.33%,16.67%.
Below is my code, it gets right the number of votes but when it comes to percentage it just shows 0.0% in all cases.I hope you guys can help me out.
import java.util.Scanner;
public class ElectionPercentage {
public static void main(String[]args){
//https://acm.timus.ru/problem.aspx?space=1&num=1263
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many candidates are : ");
int candidates = sc.nextInt();
int [] allCandidates = new int[candidates];
int startingCandidate = 1;
for(int i = 0; i < candidates;i++){
allCandidates[i] = startingCandidate++; //now value of the first element will be 1 and so on.
}
//for testing System.out.println(Arrays.toString(allCandidates));
System.out.println("enter the number of electors : ");
int electors = sc.nextInt();
int [] allVotes = new int[electors];
for(int i =0;i < electors;i++){
System.out.println("for which candidate has the elector voted for :");
int vote = sc.nextInt();
allVotes[i] = vote; //storing all electors in array
}
System.out.println();
int countVotes = 0;
double percentage;
for(int i = 0;i<allCandidates.length;i++){
for(int k = 0; k < allVotes.length;k++){
if(allCandidates[i]==allVotes[k]){
countVotes++;
}
}
System.out.println("Candidate "+allCandidates[i]+" has : "+countVotes+" votes.");
percentage = ((double)(countVotes/6)*100);
System.out.println(percentage+"%");
countVotes = 0;
}
}
}
countVotes is an int 6 is also an int. Thus, (countVotes/6) which is in your code, near the end, is integer division. 11/6 in integer division is 1. 5/6 is 0. It rounds by lopping off all decimals. That's probably not what you want, especially because you try to cast it to double afterwards.
You're casting the wrong thing. But you don't even need the cast at all; if either side is double, the whole thing becomes double division. So, instead of: percentage = ((double)(countVotes/6)*100); try percentage = 100.0 * countVotes / 6.0;
Also, presumably, that 6 should really be a variable that counts total # of votes, no? i.e. electors, so: percentage = 100.0 * countVotes / electors;
The fact that we kick off the math with 100.0 means it'll be double math all the way down.
countVotes is an int. When you do (double)(countVotes/6), (countVotes/6) happens first. This evaluates to 0 since both are int. To fix this, change 6 to 6.0.
(double)(countVotes/6.0)*100
In which case, the cast to double is no longer needed.
(countVotes/6.0)*100

Compare randomly generated number between user input

I am a cs student and i have an assignment that I'm not sure how to complete here is the prompt,
"Develop a Java console application for a simple game of guessing at a secret five-digit code (a random number from 10000 to 99999). When the user enters a guess at the code, the program outputs two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 53840 and the user guesses 83241, the digits 3 and 4 are in the correct positions. Thus, the program should respond with 2 (number of correct digits) and 7 (sum of the correct digits). Allow the user to guess until s/he gets it correct."
basically the part I am stuck on is how to find which numbers are correct numbers in common and add them together. Here is my code so far.
Random rand = new Random();
int secretNumber = rand.nextInt(99999 - 10000 + 1) + 10000;
System.out.println(secretNumber);
Scanner consoleScanner = new Scanner(System.in);
int guess;
do {
System.out.print("Please enter a 5-digit code (your guess): ");
guess = consoleScanner.nextInt();
if (guess == secretNumber)
System.out.println("****HOORAY! You solved it. You are so smart****");
else if (guess > 99999 || guess < 10000)
System.out.println("Guess must be a 5-digit code between 10000 and 99999.\n");
} while (guess != secretNumber);
any help would be greatly appreciated.
You have a number. I'm going to call it blarg. Let's say blarg is a double.
You also have a number called input.
String blargString = Double.toString(blarg);
String inputString = Double.toString(input);
ArrayList<Integer[]> indexNumberList = new ArrayList<Integer[]>();
int n = 0;
for (char c : blargString.toCharArray()) {
n++;
if (c == inputString.toCharArray()[n]) {
Integer[] entry = new Integer[2];
entry[0] = n;
entry[1] = Character.getNumericValue(c);
indexNumberList.add(entry);
}
}
Now you have a list of Integer pairs. Do what you will with it. For each pair, entry[0] is the location in the number, the index, and entry[1] is the value.
Integer.toString(int) returns the string representation of an integer. You can compare the strings returned from Integer.toString(secretNumber) and Integer.toString(guess) character-by-character to determine which digits differ.
Here's how I'd go about solving that problem. My solution is quick but probably naive. Convert the number the user enters and your generated number to strings and then to two arrays of 5 bytes each. Scan through the arrays and compare two corresponding bytes at a time. Let the user know that the position of a digit was guessed correctly if two corresponding bytes are equal. Below, I show you how you can get the array of bytes you need.
byte[] a = Integer.toString(guess).getBytes();
byte[] b = Integer.toString(secretNumber).getBytes();
So you have 2 5-digit numbers that you need to compare.
I would recommend you to do this with a loop:
//Make copies so we can modify the value without changing
// the original ones.
int tempGuess = guess;
int tempSecret = secretNumber;
//Create variables for the output
int numCorrect = 0;
int sumCorrect = 0;
for(int i = 0; i < 5; i++) //for each of the digits
{
//Get the last digit of each number and remove it from the number:
int lastGuess = tempGuess%10;
tempGuess/=10;
int lastSecret = tempSecret%10;
tempSecret/=10;
//Compare both digits:
if(lastGuess == lastSecret)
{
//Found a match: Increas number of found by one
numCorrect++;
//Add value of digit to sum
sumCorrect += lastGuess;
}
}
//numCorrect now contains the number of matching digits
//sumCorrect now contains the sum of matchig digits
The solution can be address like:
define an counter for the coincidences and an accumulator for the adition of those
make a loop through the guess and compare char by char if the input at any given char match the random number, if so:
increase counter by one and add to the accumulator the integer value of the char.
Example:
final String s1 = Integer.toString(secretNumber);
final String s2 = Integer.toString(guess);
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) {
counter++;
acumm = Character.getNumericValue(s1.charAt(i));
}
}
System.out.println("There is/are " + counter + " coincidences");
System.out.println("The addition of those is: " + acumm);
you could use integers, use modulus and divide to get the digit you want.
53840 % 100000 / 10000 = 5
53840 % 10000 / 1000 = 3
loop and compare

Retrieve numbers after comma (from double numbers)

Imagine that I have 4,81 (double), how can i get the figures after the comma?
I want to receive 8 as a Integer and 1 as another.
Thanks
Doubles are tricky to work with when you're interested in decimal properties such as the decimal digits of the fractional part.
I suggest you let String.valueOf do the transformation to decimal digits and work with the resulting string.
double d = 4.81;
String s = String.valueOf(d);
for (int i = s.indexOf(".") + 1; i < s.length(); i++) {
int digit = Character.getNumericValue(s.charAt(i));
System.out.println(digit);
}
Output:
8
1
You can always make this kind of loop:
double number = 4,81;
while (condition) {
number *= 10;
int nextNumber = Math.floor(number) % 10;
}

I need to separate a integer then add the digits together in java

Good morning, I am on now to lesson 4 and am having a bit of trouble using loops. Please note that I have seen it resolved using strings but I am trying to grasp loops.
The reason for the trouble is I need to show both answers: The integer broken into individual number ex: 567 = 5 6 7
And then 567 = 18
I am able to get the integer added together but am not sure on how to separate the integer first and then add the individual numbers together. I am thinking that I need to divide down to get to 0. For instance if its a 5 digit number /10000, /1000, /100, /10, /1
But what if the user wants to do a 6 or 7 or even a 8 digit number?
Also I am assuming this would have to be first and then the addition of the individual integers would take place?
thanks for the guidance:
import java.util.Scanner;
public class spacing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
System.out.print("Enter a your number: ");
n = in.nextInt();
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
System.out.println("Sum: " + sum);
}
}
Since this is a lesson, I won't give you the solution outright, but I will give you some hints:
You're only thinking in int. Think in String instead. :) This will also take care of the case where users provide you numbers with a large number of digits.
You will need to validate your input though; what if someone enters "12abc3"?
String.charAt(int) will be helpful.
Integer.parseInt(String) will also be helpful.
You could also look at using long instead of int; long has an upper limit of 9,223,372,036,854,775,807 though.
//I assume that the input is a string which contains only digits
public static int parseString(String input)
{
char[] charArray = input.toCharArray();
int sum = 0;
for (int index = 0; index < input.length; index++)
{
sum += Integer.parseInt(charArray[index] + "");
}
return sum;
}
Use the function above, pass your input to the function and use the output as you like.

Iterate through each digit in a number

I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
long addSquaresOfDigits(int number) {
long result = 0;
int tmp = 0;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);
Assuming the number is an integer to begin with:
int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;
for (int i = 0; i < strLength; ++i) {
int digit = Integer.parseInt(strNum.charAt(i));
sum += (digit * digit);
}
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
public static ArrayList<Integer> splitViaString(long number) {
ArrayList<Integer> result = new ArrayList<>();
String s = Long.toString(number);
for (int i = 0; i < s.length(); i++) {
result.add(s.charAt(i) - '0');
}
return result; // MSD at start of list
}
vs
public static ArrayList<Integer> splitViaModulo(long number) {
ArrayList<Integer> result = new ArrayList<>();
while (number > 0) {
int digit = (int) (number % 10);
result.add(digit);
number /= 10;
}
return result; // LSD at start of list
}
Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)
So not a lot in it really, but I was a bit surprised that String was faster
In the above example we can use:
int digit = Character.getNumericValue(strNum.charAt(i));
instead of
int digit = Integer.parseInt(strNum.charAt(i));
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
This code returns the first number (after 1) that fits your description.
public static void main(String[] args) {
int i=2;
// starting the search at 2, since 1 is also a happy number
while(true) {
int sum=0;
for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
int j=Character.getNumericValue(ch);
// getting the numeric value of the current char.
sum+=Math.pow(j, j);
// adding the current digit raised to the power of itself to the sum.
}
if(sum==i) {
// if the sum is equal to the initial number
// we have found a number that fits and exit.
System.out.println("found: "+i);
break;
}
// otherwise we keep on searching
i++;
}
}

Categories