Monday, September 13, 2021

This program prints out a 3N+1 sequence starting from a positive integer specified by the user. It also counts the number of terms in the sequence, and prints out that number.

 "Given a positive integer, N, define the '3N+1' sequence starting from N as follows: If N is an even number, then divide N by two; but if N is odd, then multiply N by 3 and add 1. Continue to generate numbers in this way until N becomes equal to 1. For example, starting from N = 3, which is odd, we multiply by 3 and add 1, giving N = 3*3+1 = 10. Then, since N is even, we divide by 2, giving N = 10/2 = 5. We continue in this way, stopping when we reach 1. The complete sequence is: 3, 10, 5, 16, 8, 4, 2, 1.




import java.util.Scanner;
public class BSIT
{
public static void main(String[] args)
{
Scanner readme = new Scanner(System.in);

int num; // starting point how much number
int counter; // for counting the terms

System.out.print("Starting point for sequence: ");
num = readme.nextInt();

while (num <= 0)
{
System.out.print(
"The starting point must be positive and start with 1. Please try again: " );
num = readme.nextInt();
}
// At this point, we know that N > 0

counter = 0; // count the

while (num != 1)
{
if (num % 2 == 0) // id number input is even
num = num / 2;

else
num = 3 * num + 1; // id number input is odd
System.out.println(num);
counter = counter + 1;
}

System.out.println();
System.out.print("There were ");
System.out.print(counter);
System.out.println(" terms in the sequence.");

}

}




































































No comments:

Post a Comment

Contact Us

Contact Form

Name

Email *

Message *