In: Computer Science
Write a java program that asks the user for a positive integer N and then calculates a new value for N based on whether it is even or odd: if N is even, the new N is N/2. (Use integer division.) if N is odd, the new N is 3*N + 1. Repeat with each new N until you reach the value 1. For example, say the initial value is 12. Then the successive values are:
12 (even, next value is 12/2)
6 (even, next value is 6/2)
3 (odd, next value is 3*3+1)
10 (even, next value is 10/2)
5 (odd, next value is 3*5+1)
16 (even, next value is 16/2)
8 (even, next value is 8/2)
4 (even, next value is 4/2)
2 (even, next value is 2/2)
1 (stop calculation)
Source Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class NewN
{
public static void main (String[] args) throws
java.lang.Exception
{
Scanner input=new Scanner(System.in);
System.out.println("Enter a positive value for N: ");
int N=input.nextInt(); //taking input from user, the value of
N..
while(N!=1) // while loop is iterated until N becomes 1..
{
if(N%2==0) // condition for even number is divisible by
2..
{
N=N/2; //as given in question if even..
System.out.println("Even, Hence: "+N+" ");
}
else // a number can be either even or odd. So, if it is not
even definitely it would be odd.
{
N=3*N+1; //as given in question if odd..
System.out.println("Odd, Hence: "+N+" ");
}
}
System.out.println("STOP CALCULATION");
}
}
OUTPUT:
NOTE: Since, class name was not given I have taken it myself i.e. "NewN".
I have mentioned the comments wherever necessary in the code, please copy the entire code and save it with "NewN.java" then, compile and run.
Hope it helps..!!
For any problem or query please feel free to comment.