Incorrect output for Project Euler #14 output - java

I'm trying to implement the algorithm to solve Project Euler Problem #14, which asks to find a number in a given range that outputs the largest Collatz conjecture sequence length. My code is below:
import java.util.ArrayList;
class Collatz {
private static ArrayList<ArrayList<Long>> previousNums = new ArrayList();
public static int seqLen(int x) {
ArrayList<Long> colSeq = new ArrayList();
long val = x;
colSeq.add(val);
while (val > 1) {
if (val%2 == 0) {
val/=2;
if (val < previousNums.size()) /*used to check if index exists*/{
colSeq.addAll(previousNums.get((int)val));
break;
}
else colSeq.add(val);
}
else {
val = 3*val + 1;
if (val < previousNums.size()) {
colSeq.addAll(previousNums.get((int)val));
break;
}
else colSeq.add(val);
}
}
previousNums.add(colSeq);
return colSeq.size();
}
public static void main(String[] args) {
int greatestNum = 0;
long totalVal = 0;
for (int i = 0; i<=1000000; i++) {
int collatz = seqLen(i);
if (collatz > totalVal) {}
greatestNum = i;
totalVal = collatz;
}
System.out.println(greatestNum + " " + totalVal);
}
}
The output I get is
1000000 153
While this is not the correct answer, 153 is the correct sequence length for 1 million. Based off of this, I could assume that my Collatz conjecture algorithm works, but not the comparison part. However, I can't really find anywhere else I could modify the code. Any ideas? Thank you and please pardon the possibility of this being a duplicate (not many other posts had the same problem).

Wow, a mere syntax error was the issue. Looks like I didn't pay attention to:
if (collatz > totalVal) {}
greatestNum = i;
totalVal = collatz;
Yup, didn't enclose the code with the braces.

Related

Algorithm to find `balanced number` - the same number of even and odd dividers

We define balanced number as number which has the same number of even and odd dividers e.g (2 and 6 are balanced numbers). I tried to do task for polish SPOJ however I always exceed time.
The task is to find the smallest balance number bigger than given on input.
There is example input:
2 (amount of data set)
1
2
and output should be:
2
6
This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
private static final BigDecimal TWO = new BigDecimal("2");
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int numberOfAttempts = in.nextInt();
for (int i = 0; i < numberOfAttempts; i++) {
BigDecimal fromNumber = in.nextBigDecimal();
findBalancedNumber(fromNumber);
}
}
private static boolean isEven(BigDecimal number){
if(number.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0){
return false;
}
return true;
}
private static void findBalancedNumber(BigDecimal fromNumber) {
BigDecimal potentialBalancedNumber = fromNumber.add(BigDecimal.ONE);
while (true) {
int evenDivider = 0;
int oddDivider = 1; //to not start from 1 as divisor, it's always odd and divide potentialBalancedNumber so can start checking divisors from 2
if (isEven(potentialBalancedNumber)) {
evenDivider = 1;
} else {
oddDivider++;
}
for (BigDecimal divider = TWO; (divider.compareTo(potentialBalancedNumber.divide(TWO)) == -1 || divider.compareTo(potentialBalancedNumber.divide(TWO)) == 0); divider = divider.add(BigDecimal.ONE)) {
boolean isDivisor = potentialBalancedNumber.remainder(divider).compareTo(BigDecimal.ZERO) == 0;
if(isDivisor){
boolean isEven = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) == 0;
boolean isOdd = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0;
if (isDivisor && isEven) {
evenDivider++;
} else if (isDivisor && isOdd) {
oddDivider++;
}
}
}
if (oddDivider == evenDivider) { //found balanced number
System.out.println(potentialBalancedNumber);
break;
}
potentialBalancedNumber = potentialBalancedNumber.add(BigDecimal.ONE);
}
}
}
It seems to work fine but is too slow. Can you please help to find way to optimize it, am I missing something?
As #MarkDickinson suggested, answer is:
private static void findBalancedNumberOptimized(BigDecimal fromNumber) { //2,6,10,14,18,22,26...
if(fromNumber.compareTo(BigDecimal.ONE) == 0){
System.out.println(2);
}
else {
BigDecimal result = fromNumber.divide(new BigDecimal("4")).setScale(0, RoundingMode.HALF_UP).add(BigDecimal.ONE);
result = (TWO.multiply(result).subtract(BigDecimal.ONE)).multiply(TWO); //2(2n-1)
System.out.println(result);
}
}
and it's finally green, thanks Mark!

Staircase problem: How to print the combinations?

Question:
In this problem, the scenario we are evaluating is the following: You're standing at the base of a staircase and are heading to the top. A small stride will move up one stair, and a large stride advances two. You want to count the number of ways to climb the entire staircase based on different combinations of large and small strides. For example, a staircase of three steps can be climbed in three different ways: three small strides, one small stride followed by one large stride, or one large followed by one small.
The call of waysToClimb(3) should produce the following output:
1 1 1,
1 2,
2 1
My code:
public static void waysToClimb(int n){
if(n == 0)
System.out.print("");
else if(n == 1)
System.out.print("1");
else {
System.out.print("1 ");
waysToClimb(n - 1);
System.out.print(",");
System.out.print("2 ");
waysToClimb(n - 2);
}
}
My output:
1 1 1,
2,
2 1
My recursion doesn't seem to remember the path it took any idea how to fix it?
Edit:
Thank you guys for the responses. Sorry for the late reply
I figured it out
public static void waysToClimb(int n){
String s ="[";
int p=0;
com(s,p,n);
}
public static void com(String s,int p,int n){
if(n==0 && p==2)
System.out.print(s.substring(0,s.length()-2)+"]");
else if(n==0 && p !=0)
System.out.print(s+"");
else if(n==0 && p==0)
System.out.print("");
else if(n==1)
System.out.print(s+"1]");
else {
com(s+"1, ",1,n-1);
System.out.println();
com(s+"2, ",2,n-2);
}
}
If you explicity want to print all paths (different than counting them or finding a specific one), you need to store them all the way down to 0.
public static void waysToClimb(int n, List<Integer> path)
{
if (n == 0)
{
// print whole path
for (Integer i: path)
{
System.out.print(i + " ");
}
System.out.println();
}
else if (n == 1)
{
List<Integer> newPath = new ArrayList<Integer>(path);
newPath.add(1);
waysToClimb(n-1, newPath);
}
else if (n > 1)
{
List<Integer> newPath1 = new ArrayList<Integer>(path);
newPath1.add(1);
waysToClimb(n-1, newPath1);
List<Integer> newPath2 = new ArrayList<Integer>(path);
newPath2.add(2);
waysToClimb(n-2, newPath2);
}
}
initial call: waysToClimb(5, new ArrayList<Integer>());
Below mentioned solution will work similar to Depth First Search, it will explore one path. Once a path is completed, it will backtrace and explore other paths:
public class Demo {
private static LinkedList<Integer> ll = new LinkedList<Integer>(){{ add(1);add(2);}};
public static void main(String args[]) {
waysToClimb(4, "");
}
public static void waysToClimb(int n, String res) {
if (ll.peek() > n)
System.out.println(res);
else {
for (Integer elem : ll) {
if(n-elem >= 0)
waysToClimb(n - elem, res + String.valueOf(elem) + " ");
}
}
}
}
public class Test2 {
public int climbStairs(int n) {
// List of lists to store all the combinations
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// initially, sending in an empty list that will store the first combination
csHelper(n, new ArrayList<Integer>(), ans);
// a helper method to print list of lists
print2dList(ans);
return ans.size();
}
private void csHelper(int n, List<Integer> l, List<List<Integer>> ans) {
// if there are no more stairs to climb, add the current combination to ans list
if(n == 0) {
ans.add(new ArrayList<Integer>(l));
}
// a necessary check that prevent user at (n-1)th stair to climb using 2 stairs
if(n < 0) {
return;
}
int currStep = 0;
// i varies from 1 to 2 as we have 2 choices i.e. to either climb using 1 or 2 steps
for(int i = 1; i <= 2; i++) {
// climbing using step 1 when i = 1 and using 2 when i = 2
currStep += 1;
// adding current step to the arraylist(check parameter of this method)
l.add(currStep);
// make a recursive call with less number of stairs left to climb
csHelper(n - currStep, l, ans);
l.remove(l.size() - 1);
}
}
private void print2dList(List<List<Integer>> ans) {
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans.get(i).size(); j++) {
System.out.print(ans.get(i).get(j) + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Test2 t = new Test2();
t.climbStairs(3);
}
}
Please note this solution will timeout for larger inputs as this isn't a memoized recursive solution and can throw MLE(as I create a new list when a combination is found).
Hope this helps.
if anyone looking for a python solution, for this problem.
def way_to_climb(n, path=None, val=None):
path = [] if path is None else path
val = [] if val is None else val
if n==0:
val.append(path)
elif n==1:
new_path = path.copy()
new_path.append(1)
way_to_climb(n-1, new_path, val)
elif n>1:
new_path1 = path.copy()
new_path1.append(1)
way_to_climb(n-1, new_path1, val)
new_path2 = path.copy()
new_path2.append(2)
way_to_climb(n-2, new_path2, val)
return val
Note: it is based on the #unlut solution, here OP has used a top-down recursive approach. This solution is for all people who looking for all combination of staircase problem in python, no python question for this so i have added a python solution here
if we use a bottom-up approach and use memorization, then we can solve the problem faster.
Even though you did find the correct answer to the problem with your code, you can still improve upon it by using just one if to check if the steps left is 0. I used a switch to check the amount of steps taken because there are only 3 options, 0, 1, or 2. I also renamed the variables that were used to make the code more understandable to anyone seeing it for the first time, as it is quite confusing if you are just using one letter variable names. Even with all these changes the codes run the same, I just thought it might be better to add some of these things for others who might view this question in the future.
public static void climbStairsHelper(String pathStr, int stepsTaken, int stepsLeft)
{
if(stepsLeft == 0)
{
switch(stepsTaken)
{
case 2:
System.out.print(pathStr.substring(0, pathStr.length() - 2) + "]");
break;
case 1:
System.out.print(pathStr + "");
break;
case 0:
System.out.print("");
break;
}
}
else if(stepsLeft == 1)
{
System.out.print(pathStr + "1]");
}
else
{
climbStairsHelper(pathStr + "1, ", 1, stepsLeft - 1);
System.out.println();
climbStairsHelper(pathStr + "2, ", 2, stepsLeft - 2);
}
}`
`

given int X,find Y such that (X+Y) is pallindrome in binary format.works fine with values upto 12345 not working with values 123456 and above

public class aevi{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
long num=s.nextLong();
long i=0,j;
while(i<num)
{
long p=1,sum=0,reversesum=0;
j=num+i;
while(j>0)
{
System.out.print(j%2+" ");
sum+=(j%2)*p;
p=p*10;
j=j/2;
}
long r=sum;
System.out.print(r+" ");
while(sum!=0)
{
reversesum=(reversesum*10)+(sum%10);
sum=sum/10;
}
System.out.println(reversesum);
if(reversesum==r)
{System.out.println(i);
break;}
i++;
}
}
}
whats wrong with this code.The program is about " given a number X.find minimium positive integer Y required to make binary representation of
(X+Y) palindrome.for eg:X=6 Y=1".It works fine with values upto 12345 but it is not working with values 123456 and above.
To tell the truth, it is hard to read your code and find problem. I think it is too complicated with such simple problem. I offer you another solution.
E.g. you entered x=6, this is 110 in binary format. Your goal is to find another minimal value y that x+y=<binary palindrome>. For 110, maximum palindrome id 111 which is 7. So, all you need is just find a minimal 0 <= y <= (7-6) where x+y=<binary palindrome>.
Here is the code example. It is pretty easy and simple.
public static long toBinaryPalindrome(long num) {
for (long i = 0, total = allBits(Long.toBinaryString(num).length()) - num; i <= total; i++)
if (isBinaryPalindrome(num + i))
return i;
return -1;
}
private static boolean isBinaryPalindrome(long num) {
String str = Long.toBinaryString(num);
return str.equals(new StringBuilder(str).reverse().toString());
}
private static long allBits(int len) {
long res = 0;
for (int i = 0; i < len; i++)
res |= 1 << i;
return res;
}

Recursive print Factorial

So I did search and read abut every factorial listing on this site but I cannot seem to figure out what is wrong with my code. Iv tried multiple different return methods but they all keep failing. Any ideas?
public class RecursivelyPrintFactorial {
public static void printFactorial(int factCounter, int factValue) {
int nextCounter = 0;
int nextValue = 0;
if (factCounter == 0) // Base case: 0! = 1
System.out.println("1");
}
else if (factCounter == 1) // Base case: print 1 and result
System.out.println(factCounter + " = " + factValue);
}
else { // Recursive case
System.out.print(factCounter + " * ");
nextCounter = factCounter - 1;
nextValue = nextCounter * factValue;
}
return factValue * printFactorial(factValue - factCounter);
}
}
public static void main (String [] args) {
int userVal = 0;
userVal = 5;
System.out.print(userVal + "! = ");
printFactorial(userVal, userVal);
}
}
I have a feeling I have the equation incorrect in my return but iv tried every combination I can think of. Its driving me insane. Every one reports an error. Any ideas?
return factValue * printFactorial(factValue - factCounter);
I assume that you should be using the "next" values instead of these.
Edit: Also note that the function takes two parameters and is void. Returning factValue times void doesn't make sense.

Project Euler prob. 3 IndexOutOfBoundsException

I'm trying to use a Sieve of Eratosthenes method for finding the largest prime factor of a large number (problem 3 in Project Euler).
My syntax seems to be correct, and i am using Long (not int), but I'm getting the following error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at problem3.ProblemThree.Factor(ProblemThree.java:49)
at problem3.ProblemThree.Recursion(ProblemThree.java:37)
at problem3.ProblemThree.main(ProblemThree.java:83)
I don't know why this is happening. Could somebody please tell me what I'm doing wrong here?
package problem3;
import java.util.List;
import java.util.ArrayList;
public class ProblemThree
{
//initializing variables and lists
long factorNo;
long nowTesting;
int i;
List<Long> allPrimeList = new ArrayList<Long>();
List<Long> ourPrimes = new ArrayList<Long>();
ProblemThree(long x) //constructor; the input "x" is the number whose highest prime factor is being sought
{
factorNo = x;
}
void initialize() //use the workaround initialization (add 2 to the allPrimesList, set nowTesting to 3).
//If the factorNo is even, add 2 to the primes list
//TODO: need more elegant solution
{
allPrimeList.add((long) 2);
nowTesting=3;
if(factorNo % 2 == 0) ourPrimes.add((long) 2);
i = 0;
}
void recursion() //keep factoring the next nowTesting until the next nowTesting is greater than half of the factorNo
{
while (nowTesting <= (factorNo/2))
{
nowTesting = factor(nowTesting);
}
System.out.println(ourPrimes);
}
long factor(long t) //The factorization algorithm. Lists all the factors of long t
{
nowTesting = t;
// Line 49:
if ((nowTesting % allPrimeList.get(i)) == 0)
{
i = 0;
return (nowTesting + 2);
}
else
if(i <= allPrimeList.size()) //if we have not yet reached the end of ourPrimeList
{
i++;
return nowTesting;
}
else //if the end of ourPrimeList has been reached without a single modulus==0, this number is a prime
{
allPrimeList.add(nowTesting);
if(factorNo%nowTesting==0) //if the nowTesting is a prime factor of factorNo, it will be perfectly divisible
{
ourPrimes.add(nowTesting);
}
i=0;
return (nowTesting+2);
}
}
public static void main (String[] args)
{
ProblemThree pt = new ProblemThree(600851475143L);
pt.initialize();
pt.recursion();
}
}
thank you everyone for patiently wading through my code, I realize that it must have been excruciatingly painful :)
I have just solved the problem. My previous approach seems very complicated in retrospect. This is the final solution I used, quite a bit more elegant, although it still has room for improvement:
//second attempt from the ground up!
package problem3;
public class BiggestPrime
{
long lInput;
long factorTest;
long currentHeight;
boolean divided;
public BiggestPrime(long n)
{
factorTest = 2;
currentHeight = n;
System.out.println("The prime factors of " + n + " are:");
while (factorTest<currentHeight)
{
if (divided == true) {factorTest = 2; divided = false;}
if (factorTest > currentHeight) {System.out.println("factorTest is greater than currentHeight; breaking"); break;}
if (currentHeight%factorTest==0)
{
System.out.println(factorTest);
currentHeight /= factorTest;
divided = true;
}
else { factorTest = factorTest + 1L; divided = false;}
}
if (factorTest == currentHeight)
{
System.out.println(factorTest);
}
System.out.println("The end");
}
public static void main (String[] args)
{
BiggestPrime bp = new BiggestPrime(600851475143L);
}
}
An interesting approach. Of course, nobody should solve your Euler challenges. But did you know that the second time, you enter 'factor' nowTesting is 3?
// The factorization algorithm. Lists all the factors of long t
long factor (final long nowTesting)
{
System.out.println ("entering factor: " + nowTesting);
Minor ideas:
allPrimeList.add ((long) 2);
can be written:
allPrimeList.add (2L);
and you pobably recognized the "final" in front of the 'long' parameter in factor? It helps reasoning about code, if you mark everything which isn't changed final. In practise, the consequence is, that your Javacode is cluttered with 'final' modifiers, but that's how it is. It's a sign of good code - maybe not of good design. Final could have been the default.
At line 49, shouldn't you be checking if nowTesting is divisible by i, not the ith element of allPrimes?

Categories