Recursive Number Sequence - java

I want to make a program to output this number sequence: (2),(5),(11),(23),...
where xi = 2*xi-1 + 1, and x0=2.
Here's my code:
public static int num(int n){
if(n <= 0)
return 2;
else
return ((2 * 2)+1);
}
I'm having trouble finding a way to output the numbers 11, 23 and onwards. Would it work if I set a counter variable and continuously loop around the second return statement?

Well seeing as you want it to be recursive, let's make it recursive!
public static int num(int n){
if(n <= 0)
return 2;
else
return (2 * num(n-1))+1; //Recursive call here
}
With a quick runnable method to check it:
public static void main(String[] args){
for(int i = 0; i < 10; i++){
System.out.println("num(" + i + ")=" + num(i));
}
}
Output:
num(0)=2
num(1)=5
num(2)=11
num(3)=23
num(4)=47
num(5)=95
num(6)=191
num(7)=383
num(8)=767
num(9)=1535

Related

How to calculate consecutive integers using a for loop method and a recursive method?

I need to calculate the sum of consecutive integers in 1.) a for loop method and 2.) a recursive method. Both methods are static int methods that take in two int parameters (one is the starting int and the other is the number of ints that come after it). For example, if I were to input (3, 3), the output should be 18 because 3 is the starting number and the 3 ints after are 4, 5, & 6. When you add those all up (3+4+5+6) you get 18. Both methods are doing this same math, except one is doing so with a for loop and the other is doing so recursively.
The problem I'm having here is my for loop method doesn't sum up properly. When I input (3, 3) the output is 31. Furthermore, I'm not quite sure how to write the recursive method since my for loop method doesn't work. May I get some help with this?
Also, no Arrays or ArrayLists. This code should be able to work without using those.
public static int consecSum(int startingNum, int numInts){
for (int i = numInts; i>0; i--){
startingNum += (startingNum + 1);
}
return startingNum;
}
public static int recursSum(int startingNum, int numInts) {
if (startingNum == 0) {
return 0;
} else if (numInts == 0) {
return startingNum;
}
return startingNum + recursSum(startingNum + numInts, numInts - 1);
}
3 \\startingNum (theres more code not shown where I use a scanner object to input these)
3 \\numInts
31 \\for loop output
\\The recursive method just prints an error message
For Loop
The problem in your for loop solution is what you think is the "last integer" is actually the "last sum". You meant to say
startingNum = 3
startingNum = 3 + 4
startingNum = 7 + 5
startingNum = 12 + 6
But since you're always keeping the new sum inside of startingNum itself, this is what's happening
startingNum = 3
startingNum = 3 + 4
startingNum = 7 + 8 (because startingNum + 1 = 7 + 1 = 8)
startingNum = 15 + 16
Try this instead
public static int consecSum(int startingNum, int numInts){
int nextNum = startingNum + 1;
for (int i = numInts; i>0; i--){
startingNum += nextNum;
nextNum++;
}
return startingNum;
}
Recursion
You almost have it. Based on what I see, your thought process was to have return the starting number if the number of integers is 0, otherwise return the starting number + the output of the method called on the next number. That's definitely valid. Try these edits
public static int recursSum(int startingNum, int numInts) {
if (numInts == 0) {
// eventually the numInts will become 0, meaning there's no
// numbers to add after this startingNum, so just return it
return startingNum;
}
// otherwise, if numInts > 0, that means there are other numbers to add so
// return the sum of the current number with the output of the function called
// on the next number (while not forgetting to decrease the number of integers
// we should consider after that)
return startingNum + recursSum(startingNum + 1 /* next number */, numInts - 1 /* decrease the number of integers to consider after that */);
}
The problem with the iterative solution is that you're modifying the starting point in each iteration. Instead, could use a separate variable for the sum:
public static int consecSum(int startingNum, int numInts){
int sum = 0;
for (int i = numInts; i>0; i--){
sum += (startingNum + 1);
}
return sum;
}
The recursive implementation has a similar problem:
public static int recursSum(int startingNum, int numInts) {
if (numInts == 0) {
return startingNum;
}
return startingNum + recursSum(startingNum + 1, numInts - 1);
}
Iterative approach:
public static int consecSum(int startingNum, int numInts){
int sum = startingNum++;
for (int i = numInts; i>0; i--, startingNum++;){
sum += startingNum;
}
return sum;
}
Recursive Approach:
public static int recursSum(int startingNum, int numInts) {
if (numInts < 0) {
return startingNum;
}
return startingNum + recursSum(startingNum+1, numInts - 1);
}
In your consecSum() you are updating the startingNum in the loop with startingNum += (startingNum + 1).
You should use a new variable for the result:
public static int consecSum(int startingNum, int numInts) {
int result = startingNum;
for (int i = numInts; i > 0; i--) {
result += (startingNum + i);
}
return result;
}
In your recursSum you are adding startingNum + numInts in each iteration. Just add 1:
public static int recursSum(int startingNum, int numInts) {
if (numInts <= 0) {
return startingNum;
}
return startingNum + recursSum(startingNum + 1, numInts - 1);
}
The result for (3, 3) in both cases is 18.

Collatz Conjecture Method - Java

I am just learning to use methods in Java. I am trying to use a method to output the number of steps it takes to get to 1 using the collatz conjecture. Can anyone help me understand better how to execute the method? This is what I have so far:
public static void main(String[] args) {
collatz();
}
public static void collatz(int n) {
n = 20;
int i = 0;
if (n == 1) {
} else if (n % 2 == 0) {
n = (n / 2);
} else {
n = (3 * n + 1);
}
i++;
System.out.println(i);
}
This won't work because "i" is only going to be changed at the end of your code and you are not using recursion or any sort of loop in your code. So, even if it did compile, it won't give the right answer.
This is the recursive way that I've done for you.
public class Cycle {
static int cycle2 (int num) {
if (num == 1) {
return 0;
} else {
if (num % 2 > 0) {
return 1 + cycle2(num * 3 + 1);
} else {
return 1 + cycle2(num / 2);
}
}
}
public static void main(String[] args) {
int num = 14;
System.out.println(cycle2(num));
}
}
As I understand it you're asking about the syntax (rather than the algorithm itself), so here's another version of the above:
public static void main(String[] args) {
// collatz has to be called with a value or it won't compile
collatz(20);
}
public static void collatz(int n) {
int i = 0;
// The following has to occur inside a loop or it'll only occur once
while (n > 1)
{
// The following is what's known as "ternary form" - if the first statement is true, it'll assign the first value. Otherwise it assigns the first value.
// For example,
// int a = (1 == 2 ? 10 : 20);
// will equal 20
n = (n % 2 == 0 ?
(n / 2) : // This value will be assigned if n is even
(3 * n + 1)); // This value will be assigned if n is odd
i++;
}
System.out.println(i);
}
I know this question was asked a long time ago and i had similar problem so this is my solution:
public class Collatz {
public static void main(String[] args) {
collatz();
}
/*If you have (int n) inside method then
when you are calling collatz() you need to have
value inside parentheses-collatz(20), or do simply like I did.
Also you need while loop! It will loop n (20) untill finaly get 1.
Otherwise your code will execute only once
and you will have as a result 1 step to complete instead of 7*/
private static void collatz() {
int n = 20;
int i = 0;
while (n != 1) {
if (n % 2 == 0) {
n = (n / 2);
} else {
n = (3 * n + 1);
}
i++;
}
System.out.println(i);
}
}

Memoization with recursive method in java

I am working on a homework assignment, and I have completely exhausted myself. I'm new to programming, and this is my first programming class.
this is the problem:
Consider the following recursive function in Collatz.java, which is related to a famous unsolved problem in number theory, known as the Collatz problem or the 3n + 1 problem.
public static void collatz(int n) {
StdOut.print(n + " ");
if (n == 1) return;
if (n % 2 == 0) collatz(n / 2);
else collatz(3*n + 1);}
For example, a call to collatz(7) prints the sequence
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
as a consequence of 17 recursive calls. Write a program that takes a command-line argument N and returns the value of n < N for which the number of recursive calls for collatz(n) is maximized. Hint: use memoization. The unsolved problem is that no one knows whether the function terminates for all positive values of n (mathematical induction is no help because one of the recursive calls is for a larger value of the argument).
I have tried several things: using a for loop, trying to count the number of executions with a variable incremented each time the method executed, and hours of drudgery.
Apparently, I'm supposed to use an array somehow with the memoization. However, I don't understand how I could use an array when an array's length must be specified upon initiation.
Am I doing something completely wrong? Am I misreading the question?
Here is my code so far. It reflects an attempt at trying to create an integer array:
public class Collatz2 {
public static int collatz2(int n)
{
StdOut.print(n + " ");
if (n==1) {return 1;}
else if (n==2) {return 1;}
else if (n%2==0) {return collatz2(n/2);}
else {return collatz2(3*n+1);}
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
StdOut.println(collatz2(N));
}
}
EDIT:
I wrote a separate program
public class Count {
public static void main(String[] args) {
int count = 0;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
count++;
}
StdOut.println("count is " + count);
}
}
I then used piping: %java Collatz2 6 | java Count
and it worked just fine.
Since you are interested in the maximum sequence size and not necessarily the sequence itself, it is better to have collatz return the size of the sequence.
private static final Map<Integer,Integer> previousResults = new HashMap<>();
private static int collatz(int n) {
int result = 1;
if(previousResults.containsKey(n)) {
return previousResults.get(n);
} else {
if(n==1) result = 1;
else if(n%2==0) result += collatz(n/2);
else result += collatz(3*n + 1);
previousResults.put(n, result);
return result;
}
}
The memoization is implemented by storing sequence sizes for previous values of n in Map previousResults.
You can look for the maximum in the main function:
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int maxn=0, maxSize=0;
for(int n=N; n>0; n--) {
int size = collatz(n);
if(size>maxSize) {
maxn = n;
maxSize = size;
}
}
System.out.println(maxn + " - " + maxSize);
}
The trick here is to write a recursive method where an argument is the value you want to "memoize". For instance, here is a version of a method which will return the number of steps needed to reach 1 (it supposes that n is greater than or equal to 1, of course):
public int countSteps(final int n)
{
return doCollatz(0, n);
}
public static int doCollatz(final int nrSteps, final int n)
{
if (n == 1)
return nrSteps;
final int next = n % 2 == 0 ? n / 2 : 3 * n + 1;
return doCollatz(nrSteps + 1, next);
}
If you were to record the different steps instead, you'd pass a List<Integer> as an argument and .add() to it as you went through, etc etc.

Using loops to compute factorial numbers, Java

I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */

Java Program Calculation

Write a program in Java to calculate the following:
1+2-3+4-5 …-99+100
this program is provably very simple but I am a beginner to java and this is what i have so far I'm not sure if i am in the right path
I get one java: 13 error message error:not a statement sub;
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0;
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub;
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
This is complaining about this line:
sub;
This is not a valid instruction, which is why the compiler is yelling at you.
In the following:
if(num%2 == 0){
sum=sum+num;
}
sub;
That last line sub; is not a Java statement. You probably want to delete it.
Update:
Looks like you want to add even and subtract odd (except for 1 which you want to add). If I understood the requirement properly:
You can start by declaring two variables as follows:
int sum = 1; //this will add 1
int n = 2;
Loop condition should be as follows:
while(n <= 100) { //because you want to include 100 also
Then on each iteration of the loop:
If n is even add it to sum, else if n is odd subtract it from sum.
After that increment n by 1.
Finally, print the value of sum.
You can using simple way to implement it :
public static void main(String[] args) {
int sum = 1;
for (int i = 2; i < 100; i++) {
if (i % 2 == 0) {
sum = sum + i;
} else {
sum = sum - i;
}
}
System.out.println(sum);
}
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0;
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub; <-- sub is not a statment
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
You are on the right track, with a little trial and error you will get it :-) The cause of your problem is commented in the code above, in the middle of your program you have a random sub; on its own line. sub doesn't have a meaning in that context so the compiler doesn't know how to treat it.
1) You can't have 2 variables with the same name sum
2) You need to declare and initialize a variable before you use it
3) What does the statement sub; signify?
Make all the chages mentioned above and try!
Well, you declare "sum" twice, and "sub;" isn't a valid expression.
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0; // second declaration? should probably be num, right?
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub; // what's this doing here?
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
public class Loop {
public static void main(String[] args) {
int sum = 1;
int sub = 0;
for (int i = 2; i <= 100; i += 2)
//sum =sum+i;
sum +=i;
System.out.println(sum);
for (int i = 3; i <= 100; i += 2)
sub += i;
System.out.println(sub);
System.out.println("Sum is: " +(sum-sub));
}
}
Try this code will give you your desired result

Categories

Resources