Collatz Sequence - printing every sequence from 1 until N - java

I have this HW assignment that I'm stuck in:
I need to write the sequence from 1 until N given seed.
for example:
if user inputs 4 v then I need to write every line from the first sequence until the 4th and then write down how many have reached 1 in the end and count the number of numbers.
example:
1 4 2 1 (4)
2 1 (2)
3 10 5 16 8 4 2 1 (8)
4 2 1 (3)
s.o.p :The first 4 hailstone sequences reached 1.
if user inputs 7 c then I only need to write the sentence The first 4 hailstone sequences reached 1.
so far I've written the code for the v part,
the part that works:
public class Collatz {
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
String str = String.valueOf(args[1]);
int counter = 1;
if (str.equals("v")) {
while (n != 1)
{
System.out.print(n + " ");
// If n is odd
if ((n & 1) == 1) {
n = 3 * n + 1;
}
// If even
else{
n = n / 2;
}
counter++;
}
// Print 1 at the end
System.out.print(n + " (" + counter + ")");
}
}
}
I have tried putting a for loop to print from 1 to n in order to print like my example but it doesn't, my attempt:
` for (int i = 1; i < n; i = i+1){
while (i!= 1) {
System.out.print(i + " ");
// If n is odd
if ((i & 1) == 1)
i = 3 * i + 1;
// If even
else
i = i / 2;
}
// Print 1 at the end
System.out.print(i); `
no go. please help me debug this.

Solved it:
add: before the while
for (i = 1; i <= n; i = i+1){
hail = i; // we need to make sure i isn't run over
int counter = 1;

Related

Issue with getting this java program to display the proper whitespace in the answer

So my problem is, my output seems to be correct except it is giving me 0/10 for credit because of the whitespace after the output counts down to one in each situation. It is saying I need a newline after the one but I have tried several things and it's the same output every time.
2.31 LAB: Hailstone sequence
Given a positive integer n, the following rules will always create a sequence that ends with 1, called the hailstone sequence:
If n is even, divide it by 2
If n is odd, multiply it by 3 and add 1 (i.e. 3n +1)
Continue until n is 1
Write a program that reads an integer as input and prints the hailstone sequence starting with the integer entered. Format the output so that ten integers, each separated by a tab character (\t), are printed per line.
The output format can be achieved as follows:
System.out.print(n + "\t");
Ex: If the input is:
25
the output is:
25 76 38 19 58 29 88 44 22 11
34 17 52 26 13 40 20 10 5 16
8 4 2 1
import java.util.Scanner;
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int n;
n = scnr.nextInt();
System.out.print(n + "\t");
int count = 1;
while (n > 1) {
if (n % 2 == 0) {
n = n * 1 / 2;
} else {
n = 3 * n + 1;
}
System.out.print(n + "\t");
count++;
if (count % 10 == 0) {
System.out.print("\n");
}
}
}
This is what I came up with and I am new to java so it is probably something I am overthinking, any thoughts would be appreciated.
"enter image description here" is not an image description
If nothing works, I guess you can trick it by just skipping the tab on the 10'th print. So instead of your normal System.out.print(n + "\t"); print try:
if ((count + 1) % 10 == 0) {
System.out.print(n);
} else {
System.out.print(n + "\t");
}
instead of your normal print.
I figured it out, I just needed to change the order of the code a little and make (n != 1) and System.out.print(n) at the very end. Thanks for the help.
try this, changed the print condition to exclude the tab for end value and when n is 1.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int n;
n = scnr.nextInt();
System.out.print(n + "\t");
int count = 1;
while (n > 1) {
if (n % 2 == 0) {
n = n * 1 / 2;
} else {
n = 3 * n + 1;
}
count++;
if (count % 10 == 0) {
System.out.println(n);
}else{
if(n==1) {
System.out.print(n);
}else{
System.out.print(n + "\t");
}
}
}
}

Cannot print out 1 when doing Collatz contejure

I cannot print the 1 when wanting to program the Collatz contejure. Please help thanks.
Here is the problem: Given natural number n. Generate a sequence of integers, described in the Collatz conjecture:
Here is my code (Not snippet as it isn't clear (sample Input and Output at bottom):
import java.util.Scanner;
class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
while (n > 1) {
System.out.println(n);
if (n % 2 == 0) {
n = n / 2;
} else {
n = (3 * n) + 1;
}
}
}
}
SAMPLE INPUT: 17
OUTPUT: 17 52 26 13 40 20 10 5 16 8 4 2
Need to print 1 as well
Just print 1 at the end of the loop.
while (n > 1) {
System.out.println(n);
if (n % 2 == 0) {
n = n / 2;
} else {
n = (3 * n) + 1;
}
}
System.out.println(1);
When demonstrating the Collatz Conjecture, you normally print after the computation, so move the print statement to the end of the loop. If you want to show what entered value was used to start the process, print it first, outside the loop.
System.out.println("Starting with " + n);
while (n > 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = (3 * n) + 1;
}
System.out.println(n);
}

Want to print last sentence

You must deliver exactly N kilograms of sugar to a candy store. The sugar made in the sugar factory is contained in a bag. The bag has 3 kg bag and 5 kg bag.
I try to carry as little bags as possible. For example, when you need to deliver 18 kilograms of sugar, you can take 6 bags of 3 kilograms, but if you deliver 3 kilograms and 3 kilograms, you can deliver a smaller number of bags.
Write a program to find out the number of bags you should take when you have to deliver exactly N kilograms of sugar.
(3<=N<=5000 AND If you can not make exactly N kilograms, print -1.)
In case of only 4 or 7 , it is not divided so I made it to print -1.
And to get the minimum bag, I used the code below.
But when I run this, the case if it is not divided by 5 or 3, the bottom sentence should be printed out but it is not working.
I want to know how does it works. Thank you.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
if (N % 5 == 0) {
System.out.println(N / 5);
} else if (N == 4 || N == 7) {
System.out.println(-1);
} else
for (int i = 1; (N - 3 * i) % 5 != 0; i++) {
if ((N - 3 * i) % 5 == 0)
System.out.println(i + (N - 3 * i) / 5);
break;
}
}
}
Looks there is a logic issue with your solution. Try the following :
boolean isPossible = true;
if (N % 5 == 0) {
System.out.println("You need : " + (N / 5) + " bags");
} else {
int diff = 0;
for (int i = N; i > 0 && N >= 0; i--) {
if (N % 5 != 0) {
diff = N % 5;
N = N - diff;
} else {
if (diff % 3 == 0) {
System.out.println("You need : " + (N / 5 + diff / 3) + " bags");
isPossible = true;
break;
} else {
N = N - 5;
diff = diff + 5;
}
}
}
}
if (N <= 0 || !isPossible)
System.out.println(-1);
Logic is explained below :
Basically here we find the modulus of N with 5 and check if the
remainder (in the example diff) is a multiple of 3.
If the remainder (diff) is not a multiple of 3 then we reduce N by
5 and increase diff by 5. This continues until we have found a match (isPossible) or else if not found -1 is printed out.
So as far as I understand, you're trying to use the smallest amount of 3kg bags in the last for loop and you want to break out as soon as the remainder is divisible by 5kgs.
(int i = 1; (N - 3 * i) % 5 != 0; i++)
Could you not have the middle part as i < 5?
(int i = 1; i < 5; i++)
Also, you could get rid of the if condition
if (N % 5 == 0) {
part by starting i at 0, so you account for the case N is divisible by 5:
(int i = 0; i < 5; i++)
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int sum = 0;
boolean isFound = false;
for (int i = 0; i < N / 2; i++) {
for (int j = 0; j < N / 2; j++) {
if ((5 * i) + (3 * j) == N) {
sum = i + j;
isFound = true;
}
}
}
if (isFound ) {
System.out.println("You require " + sum + " bags");
} else {
System.out.println(-1);
}
Explanation:
The above code aims to find the possible combinations of the sum of the factors of 3 and 5 that give the number, i.e N:
For example:
N = 32
For each iteration, the following condition is checked.
if((5 * i) + (3 * j) == N)
The check continues until the smallest numbers that satisfy the condition are found.
5*0 + 3*0 = 0 which is not equal to 32
5*0 + 3*1 = 3 which is not equal to 32
5*0 + 3*2 = 6 which is not equal to 32
.
.
5*1 + 3*0 = 5 which is not equal to 32
5*1 + 3*1 = 8 which is not equal to 32
5*1 + 3*2 = 11 which is not equal to 32
5*1 + 3*4 = 17 which is not equal to 32
.
.
5*4 + 3*0 = 20 which is not equal to 32
5*4 + 3*1 = 23 which is not equal to 32
5*4 + 3*2 = 26 which is not equal to 32
5*4 + 3*3 = 29 which is not equal to 32
5*4 + 3*4 = 32
In this case, i=4 and j=4, i.e sum of bags required (i+j) = 8
isFound is set to true to indicate that the combination is found.
If no combination is found, isFound remains to be false, and -1 is printed.

Replacing Multiples of numbers in Fibonacci series using Flag method

As the title suggests, I have code for a Fibonacci series and my goal is to replace multiples of numbers (3, 5, 7 and combinations of them) in the series with a word. I was suggested to use a flag in my if loop to check for the printed phrase, and if the phrase is printed, to skip that number. Essentially, what I want the output to look like is:
1 1 2 skip 8 13 skip 34 55
(this is replacing multiple of three only, for now).
Instead, what I am getting is:
1 1 2 3 skip5 8 13 21 skip34 55
Here is my code as of now:
int febCount = 50;
long[] feb = new long[febCount];
feb[0] = 1;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
}
for (int i = 0; i < febCount; i++) {
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Any and all help is appreciated!
Let's walk through the code you have provided and attempt to understand why it's not working.
//The first thing we do is setup the loop to iterate through the fib numbers.
//This looks good.
for (int i = 0; i < febCount; i++) {
//Here we print out the fibonacci number we are on, unconditionally.
//This means that every fibonacci number will be printed no matter what number it is
//we don't want that.
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
//After we print the number, we check to see if it is a multiple of three.
//maybe we should be waiting to print until then?
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Now that we have walked through the code, we can propose a new solution.
Let's try updating the loop so that it wait's to print the fibonacci number until AFTER we've checked to see if it meets our conditions.
for (int i = 0; i < febCount; i++) {
if (feb[i] % 3 == 0 || feb[i] % 5 == 0 || feb[i] % 7 == 0) { //check if multiple of 3 5 or 7
System.out.println(" Skip ");
} else { //if it's not a multiple, then print the number
System.out.println(" " + feb[i]);
}
}

complex recursion formula for finding partitions

I am trying to calculate partitions of a natural number using the formula below. The formula generates two positive numbers, then two negative and so on. You stop when P(n) < 0 An example is
p(3) = p(2) + p(1) = 3
p(4) = p(3) + p(2) = 3 + 2 = 5
p(5) = p(4) + p(3) - p(0) = 5 + 3 - 1 = 7
p(6) = p(5) + p(4) - p(1) = 7 + 5 - 1 = 11
*P(0) = 1 by convention
In other words in order to calculate say P(5) you would have to calculate P(4) which equals P(3) + P(2) and and P(3) which equals P(2) + P(1) and finally - P(0) which equals 1. You would have to traverse down for each to find what they equal and then sum them. So to find a partition of a number you would have to find the partitions of all other numbers each. I have tried something as you can see the code below but it does not work. k = counter in my code.
Code:
public static long SerialFib( long n )
{
long exponent = 0;
double ex;
long counter = 1;
ex = Math.pow(-1, counter - 1);
exponent = (long) ex;
if (n < 0)
{
return 0;
}
else
{
return SerialFib((exponent * (n - ( (counter * ( (3 * counter) - 1)) /
2)))) + SerialFib((exponent * (n - ( (counter * ( (3 * counter) +1))/2))));
}
}
Counter is going to always be 1 because you aren't passing it back into SerialFib. Also, you need a base case for when n is equal to 0 it will return 1.
first base case:
if(n==0)
return 1;
SerialFib should have another parameter for counter:
SerialFib(long n, int counter)
When you call SerialFib it should look like:
SerialFib( [your formula], ++counter);

Categories