×

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

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.