Reputation: 1493
So I had to write a simple code that would compute the 3N+1 equation; where N is an integer user types in and if it is a positive integer than N = N / 2 and if negative integer than N = N * 3 + 1.
However from what I can understand, my code doesn't work after the first while loop and hence prints nothing. What am I doing wrong? New to programming and still learning so I appreciate your help :)
Code:
import java.util.Scanner;
public class ThreeNplusOneProgram {
public static void main(String[] args) {
int N; Scanner input = new Scanner(System.in); int counter;
System.out.println("Please Enter an integer: ");
N = input.nextInt();
while ( N <= 0 ) {
System.out.println("ERROR: Please Enter an integer greater than zero: ");
N = input.nextInt();
}
//So far we know that N is great than Zero
System.out.println(N);
counter = 1;
while ( N != 1 ) {
if (N == N % 2 )
N = N / 2;
else N = N * 3 + 1;
counter = counter + 1;
}
System.out.println("There were" + counter + "terms in the sequence");
}
}
Upvotes: 0
Views: 135
Reputation: 920
The problem is your if (N == N % 2)
, you might just want to check if (N >= 0)
since you do state that you are looking to check if it is a positive integer
.
Upvotes: 0
Reputation: 1114
That is wrong: if (N == N % 2 )
N % 2 returns 1 or 0. You should use if (0 == N % 2 )
to check for being odd / even.
Upvotes: 5