×

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and the corresponding Java programme in this section.

The Program is to create Java software that will read a user-provided positive number and print the 3N+1 sequence beginning with that integer. The number of terms in the sequence should likewise be counted and printed by the software.

Finding the 3N+1 Sequence

Construct the 3N+1 sequence beginning from a positive number, N, as follows:

Divide N by 2 if N is an even integer.

N must be multiplied by 3 and then added if it is an odd number.

This method of generating numbers should be continued until N equals 1.

The 3N+1 problem can be defined mathematically as follows:

 f(N)=N/2 if N is even

 f(N)=3N+1 if N is odd

Procedure

Depending on whether N is even or odd, the programme must pick multiple actions in order to compute the subsequent term. To determine whether N is even or odd, we needed an if statement for the same.

The only issue that is still present is counting. When we count, we begin with zero and add 1 each time there is something to count. To conduct the counting, we require a variable, let's say counting.

Concerning the initial step, we still have to be cautious. How can we ask the user for a positive integer? If a person types in a number instead of reading it in, it's feasible that they will enter a negative number or zero. Observing what occurs when N is zero or negative will show us that the programme will run indefinitely since N can never equal 1, which is incompatible.

The issue here is certainly not too serious, but in general terms, we should aim to create programmes that are inaccessible. To address this, one solution is to continue reading numbers until the user fills in a positive number.

Algorithm

Reading a Positive number M as input  
while M is not positive:  
display an error message;  
Reading another value M;  
Let c = 0;  //variable of count
while M is not 1:  
if M is even:  
Compute M= M/2;  
else  
Compute M = 3 * M + 1;  
Output M;  
Add 1 to c;  
Output the c;

As required, the first while loop won't break until M is a positive amount. Request another value from the user if M is not positive. If the user inputs a second non-positive integer, there is an issue. As there is only one execution of the if statement, the second input number is never examined.

After the second number is entered, the while loop verifies whether the two digits are positive before returning to the start of the loop. If not, it prompts the user for a third number and will keep doing so until they give valid input.

Java Program for 3N+1 problem

Filename: ThreeN.java

//Java Program for 3N+1 problem
//importing required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;  
//a class ThreeN is created
public class ThreeN
{  
public static void main(String args[])    
{  
//The variable for denoting the initial point of the series
int M;   
// the variable c is used to count the number of terms possible
int c;   
Scanner sc=new Scanner(System.in);  
System.out.print("Reading the first number: ");  
//an integer value is read as input from the user 
M=sc.nextInt();
// condition for checking the input value
while (M <= 0)   
{  
System.out.println("The input value should be positive. Please() re-enter the value()");  
M=sc.nextInt();  
}  
c = 0;  
//the n value in positive  
while (M != 1)   
{  
if (M % 2 == 0)  
M = M / 2;  
// the condition when M is an odd number
else  
M = 3 * M + 1;  
System.out.print(M + "\t");  
// the value of the count is incremented to 1  
c = c+1;  
}  
System.out.println();  
System.out.println("The series contains "+c+" terms");  
} // end of main
}

Output:

Reading the first number: 45
136	
68	
34	
17	
52	
26	
13	
40	
20	
10	
5	
16	
8	
4	
2	
1	
The series contains 16 terms

Related Topics

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.