×

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 run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.