Loop stops running java - java

For the code below, it stops running when "n" gets around 100,000. I need it to run until 1 million. I dont know where its going wrong, I am still learning Java so there might be simple mistakes in the code as well.
public class Problem14{
public static void main(String[] args) {
int chainLength;
int longestChain = 0;
int startingNumber = 0;
for(int n =2; n<=1000000; n++)
{
chainLength = getChain(n);
if(chainLength > longestChain)
{
System.out.println("chainLength: "+chainLength+" start: "+n);
longestChain = chainLength;
startingNumber = n;
}
}
System.out.println("longest:"+longestChain +" "+"start:"+startingNumber);
}
public static int getChain(int y)
{
int count = 0;
while(y != 1)
{
if((y%2) == 0)
{
y = y/2;
}
else{
y = (3*y) + 1;
}
count = count + 1;
}
return count;
}
}

Please use long as the data type instead of int
I will want this to come into light, that the number does flung higher than 1000000, so variable y needs long to hold it.

It's the datatype for y. It should be long. Otherwise it wraps round to -2 billion.
I thought I recognised this - it's Euler problem 14. I've done this myself.

getChain() method is causing problem it gets to negative and then it hangs forever in the loop.

Related

Why is code skipping over for loop in integer length program

Im trying to create a program to find the length of a given number. I thought i would do this by taking the number and dividing by 10 and then checking to see if the number was <= 0. I dident want to edit the global number so i created a instance version of the number and used that as the condition in the for loop.
So obviously this dident work so naturally i ended up looking in the debugger to figure out what was going on. It looks as if the program is completely skipping over the for loop any help would be appreciated.
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
for(int i = 0; instanceNumber <= 0; i++) {
instanceNumber /= 10;
numberLength = i;
}
System.out.println("Number length = " + numberLength);
// to find length of number loop division by 10
}
}
The program should use the for loop to keep dividing by 10 until the number is = to or less than than zero and for how many times the loop ran should be stored in the number length integer. In this case with the number 12321 the answer should be 6 but it prints 0.
You're telling it to loop while instanceNumber <= 0. The "test" in a for loop is a "keep going" test, not a termination test. The loop continues as long as the test is true.
From your description, you want instanceNumber > 0.
Also note Avinash Gupta's point that with your current code, you'll undercount by one. I'd address that by using a completely different loop:
int numberLength = 0;
int instanceNumber = number;
while (instanceNumber > 0) {
++numberLength;
instanceNumber /= 10;
}
That's nice and unambiguous: If instanceNumber > 0, it increments numberLength, then divides by 10 and tries again.
This will print the correct output
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
for(int i = 0; instanceNumber > 0; i++) {
instanceNumber /= 10;
numberLength = i;
}
System.out.println("Number length = " + (numberLength + 1));
}
Your code will be much more comprehensive if you use while loop for your algorithm.
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
while(instanceNumber != 0) {
instanceNumber /= 10;
numberLength += 1;
}
System.out.println("Number length = " + numberLength);
// to find length of number loop division by 10
}
Consider even more sophisticated solution:
public static void sumFirstAndLastDigit(int number) {
int numberLength = (int) (Math.log10(number) + 1);
System.out.println("Number length = " + numberLength);
}
Taken from Baeldung

Explain if block nesting

This is regarding some homework and I tried to make a range which is 10 to 40.
The code would accept two inputs within the range. The method will then check if both numbers are within the range and then if they are it would give me the product of both numbers, if not it is suppose to show me a message.
I have been working on this for quite a long time and I cant get it to work I am a complete beginner.
public class testing
{
public static int computeProduct(int first , int second)
{ int max = 40;
int min = 10;
int total = first * second;
if (min <= first) {
if (first <= max) {
if (min <= second) {
if (second <= max) {
total = first * second;
} else {
System.out.println("Number is not in range, please try again");
}
}
}
}
return total;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 10 to 40:");
int x = scanner.nextInt();
System.out.println("Enter another number between 10 to 40:");
int y = scanner.nextInt();
int total = computeProduct(x, y);
System.out.print("Product of x and y = " + total);
}
}
Expected result is to show me if the numbers are not in range but it is not doing so currently.
It gives me the product of both numbers regardless whether it is in the range.
Here:
int total = first * second;
followed by an if, follewed by:
return total;
Meaning: every time when your if evaluates to false, your method simply returns the value that you assigned initially!
What you could do: have an else block that prints the error message. Or that throws an exception.
But ideally, you should separate concerns here. Meaning:
write a method like boolean inRange(int first, int second). That method returns true or false, depending on first / second matching your criteria
if that method returns true, call compute(), otherwise print your message
In other words: your compute() method maybe shouldn't have that if block at all. Let that method compute the result, and have another method tell you whether you want to invoke compute() or not.
A "ladder" built from ifs behaves as a logical and relation. The first if passes when a condition applies, then the second if passes when both the previous condition applies and its own condition, and so on.
However for checking if something is off, violating any (even a single one) of the rules is enough, that is a logical or relation.
While it is not the best coding style, you could mechanically rewrite that structure into this via flipping the comparisions and dismantling the ladder:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (first < min) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (first > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (second < min) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (second > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
return first*second;
}
This method displays the message and returns with 0 if the input is not valid, and returns the product if everything is fine.
Then it could become an actual logical or, which is denoted as || in Java:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (first < min
|| first > max
|| second < min
|| second > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
return first*second;
}
Now as I think of it, there is nothing wrong with your original condition either, just the result has to be flipped: when the code reaches the innermost block, everything is fine, so that is the place where you could return first*second;. And if any of the if fails, you need the message and return 0;:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (min <= first) {
if (first <= max) {
if (min <= second) {
if (second <= max) {
return first*second;
}
}
}
}
System.out.println("Number is not in range, please try again");
return 0;
}
Now I am not so sure if this helps or not...
There you go :
public static int computeProduct(int first , int second)
{ int max = 40;
int min = 10;
if(first<=min || second<=min ||first>=max||second>=max)
{
System.out.println("Number is not in range, please try again");
return 0; //or return whatever you like
}
return first *second ;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 10 to 40:");
int x = scanner.nextInt();
System.out.println("Enter another number between 10 to 40:");
int y = scanner.nextInt();
int total = computeProduct(x, y);
if(total!=0){
System.out.print("Product of x and y = " + total);
}
else {
System.out.print("cannot compute as numbers are not in range");
}
}

Array size declaration

I've posted my code below. I am having a problem on the line declaring the array wrongAnswers. I've been able to get my code working before, but the problem is that some person took it upon themselves to delete all my files. I was able to get it working without using List or ArrayList. I just want to understand how I can get this working now before I try using either of those other methods. I understand that Java arrays are immutable. However, I was still somehow able to get it to work before. If someone could help me figure out what I did previously, I would be most greatful.
private Scanner keyboard = new Scanner(System.in);
private final String[] testAnswers = {
"B","D","A","A","C",
"A","B","A","C","D",
"B","C","D","A","D",
"C","C","B","D","A"};
private String[] studentAnswers = new String[20];
/*
private String[] studentAnswers = {
"B","D","A","A","C",
"A","B","A","C","D",
"B","C","D","A","D",
"C","C","B","D","A"};
*/
private int[] wrongAnswers;
private int answeredCorrectly = 0;
public void getStudentAnswers() {
for(int x = 0; x < 20; x++) {
do {
System.out.print("Enter answer for #" + (x + 1) + " : ");
this.studentAnswers[x] = keyboard.next().toUpperCase();
if (!"A".equals(this.studentAnswers[x]) &&
!"B".equals(this.studentAnswers[x]) &&
!"C".equals(this.studentAnswers[x]) &&
!"D".equals(this.studentAnswers[x])) {
System.out.println("Invalid input.");
}
} while(!"A".equals(this.studentAnswers[x]) &&
!"B".equals(this.studentAnswers[x]) &&
!"C".equals(this.studentAnswers[x]) &&
!"D".equals(this.studentAnswers[x]));
}
}
public int totalCorrect() {
int arrayLocation = 0;
for(int x = 0; x < 20; x++) {
if (this.studentAnswers[x].equals(this.testAnswers[x]))
this.answeredCorrectly++;
else
this.wrongAnswers[arrayLocation++] = x;
}
return this.answeredCorrectly;
}
public int totalIncorrect() {
return 20 - this.answeredCorrectly;
}
public boolean passed() {
return this.answeredCorrectly >= 15;
}
public void questionsMissed() {
if(this.answeredCorrectly != 20) {
for(int x = 0; x < this.wrongAnswers.length; x++) {
System.out.println(this.wrongAnswers[x]);
}
}
}
If code is well written, saving space (which is what you are trying to do) will usually cost performance and vice versa. You can achieve what you want, but you'll lose performance, as you'll see.
I find deduction to be useful when solving similar problems. Conditions:
1) Arrays are immutable
2) You want to allocate the exact amount of space that you need
Point 2 poses a question: how do you know how much space you need? Obvious answer: know how many (in)correct answers you have. Following from there you can do:
public int totalCorrect() {
for(int x = 0; x < 20; x++) {
if (this.studentAnswers[x].equals(this.testAnswers[x]))
this.answeredCorrectly++;
}
this.wrongAnswers = int[20 - this.answeredCorrectly];
// Here you want to create your wrongAnswers, but you have to go over
// the same array twice...
int arrayLocation = 0;
for(int x = 0; x < 20; x++) {
if (!this.studentAnswers[x].equals(this.testAnswers[x]))
this.wrongAnswers[arrayLocation++] = x;
}
return this.answeredCorrectly;
}
There are probably more ways to do something similar and achieve better performance too. At first sight they seem to me like bad approaches and I'd use a List, as has been proposed already, or perhaps a Set, but who knows...
private int[] wrongAnswers = new int [20];

Trailing Zeroes of a Factorial

I'm trying to solve this coding question:
Given an integer n, return the number of trailing zeroes in n!
Below is my code (codec this up using the wiki link)
public int trailingZeroes(int n) {
int count = 0, i = 5;
while(i<=n){
count+= n/i;
i*=5;
}
return count;
}
This runs for all test cases except when n = Integer.MAX_VALUE upon which I get a TLE. How can I fix this code to make it cover that test case. I have read about five articles on the net and everything seems to agree with my approach.
Much thanks.
So, I followed the long/BigInteger approach (thanks y'all):
public int trailingZeroes(int n) {
long count = 0;
for(long i= 5; n/i >= 1; i= i*5){
count+= n/i;
}
return (int)count;
}
As Iaune observed, your loop will never terminate when n is Integer.MAX_VALUE, because there is no int greater than that number (by definition). You should be able to restructure your loop to avoid that problem. For instance, this is the same basic approach, but flipped upside-down:
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
You cannot write a for or while loop where the loop counter is an int and the upper limit is <= Integer.MAX_VALUE.
What happens with a simple increment (counter++) is that the loop counter is set to that value, the body executes and then the counter is incremented which results in a negative number, Integer.MIN_VALUE. And then everything happens all over again.
Other weird things may happen when the loop counter is incremented in quantities > 1 or (as here) is multiplied: the int loop counter just can't hold a value > Integer.MAX_VALUE
Consider another approach for iterating over these numbers. Or handle MAX_VALUE separately.
Your problem is that once i gets large enough (more than Integer.MAX_INT / 5) then the line i*=5; causes i to overflow to the "wrong" value. The value in question is 5 to the 14th power, which is 6103515625, but which overflows to 1808548329.
The result of this is that the loop just keeps executing forever. i will never become a value that's not <= Integer.MAX_INT, because there's just no such int.
To avoid this, you need i to be a larger data type than an int. If you change i and count in your original code to long, this will work fine. Of course, BigInteger would also work.
public class FactorialNumberTrailingZeros {
public static void main(String[] args) {
System.out.println(trailingZeroes(1000020));
}
private static int trailingZeroes(int n) {
int count = 0;
while (n > 0 && (n % 10 == 0)) {
n /= 10;
count ++;
}
return count;
}
}
public static void main(String[] args) {
int result = findFactorialTrailingZero(100);
System.out.println("no of trailing zeros are " + result);
}
public static int findFactorialTrailingZero(int no) {
int zeros = no / 5;
int zeroIncrementNo = 25;
int zerosIncrementFactor = 1;
int nextZeroIncrenent = 5;
for (int i = 1;no >= zeroIncrementNo; i++) {
zeros=zeros+zerosIncrementFactor;
zeroIncrementNo=25*(i+1);
if(i+1==nextZeroIncrenent){
zerosIncrementFactor++;
nextZeroIncrenent=nextZeroIncrenent*5;
}
}
return zeros;
/*
[n/5]+[n/25]+[n/125]+....
if n<25 then [n/5]
if n<125 then [n/5]+[n/25]
if n<625 then [n/5]+[n/25]+[n/125]
*/
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int countTrailingZeroes(int n)
{
int res=0;
for(int i=5;i<=n;i=i*5){
res=res+n/i;
}
return res;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n;
cin>>n;
cout<<countTrailingZeroes(n);
return 0;
}
Output
25
6
Explanation:
25!=1.551121e+25 i.e contains 6 trailing zeroes
Here is my python code that could solve your problem:
def check(n):
j,ans=5,0
while j<=n:
ans=ans+n//j
j=j*5
return ans

Java comb sort caught in an infinite loop

I'm doing a combsort algorithim as a class assignment, and it loops whenever I run it. I'm not sure what I did wrong (I got it working in C++, but that was a while ago, and those skills don't translate as well as I'd like them to). I've been poring over it for an hour and a half now, and emailed some friends, but nobody has any ideas, unfortunately. I think I just need someone with some more experience to tell me what I screwed up. Thanks!
import java.util.ArrayList;
public class CombSort {
public CombSort()
{
super();
}
public ArrayList<Integer> combSort(ArrayList<Integer> sortMe)
{
int swap;
int size = sortMe.size();
int gap = size;
boolean swapped = false;
while ((gap > 1) || swapped)
{
if (gap > 1)
{
gap = (int) ((size)*((double)gap / 1.247330950103979));
}
swapped = false;
for (int i = 0; gap + i < size; ++i)
{
if (sortMe.get(i) - sortMe.get(i + gap) > 0)
{
swap = sortMe.get(i);
sortMe.set(i, sortMe.get(i + gap));
sortMe.set(i + gap, swap);
swapped = true;
}
}
}
return sortMe;
}
public static void main(String[] args)
{
ArrayList<Integer> randomArrayList = new ArrayList<Integer>(7);
randomArrayList.add(5);
randomArrayList.add(7);
randomArrayList.add(2);
randomArrayList.add(6);
randomArrayList.add(8);
randomArrayList.add(2);
randomArrayList.add(9);
CombSort combSorter = new CombSort();
System.out.println(combSorter.combSort(randomArrayList).toString());
}
}
Your gap value is getting bigger with each iteration inside the while loop, hence why it is infinitely looping.
You should only multiply the gap by the comb factor, not by the size.
(int) ((size)*((double)gap / 1.247330950103979)); should be
(int) ((double)gap / 1.247330950103979);

Categories

Resources