Issue
So, I was just trying to create a loop to run the "3n+1" formula and when I enter a negative number I get stuck in an infinite loop with a remainder of 0 and -1.
Is that correct or is my code missing something?
Here is my code:
Scanner scan = new Scanner(System.in);
number = 0;
method = 0;
int counter= 0;
if(scan.hasNextInt()){
number = scan.nextInt();
int original = number;
while(number!=1){
method = number%2;
if(method==0){
number = number/2;
}else number = number*3+1;
counter +=1;
System.out.println(number);
System.out.println("the remainder was "+method);
}
System.out.println("The original number was "+original);
System.out.println("it took " + counter+ " times to reach 1.");
}else System.out.println("please enter a number");
Solution
This conjecture holds only for natural numbers (i.e. positive integers 1, 2, 3,...). If you want to extend it to 0 and negative numbers, you will have to use some other formula. Check out "Extensions to larger domains" on https://en.wikipedia.org/wiki/Collatz_conjecture.
Answered By - Nikhil B
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.