A simple way of solving my problem would be the following method:
public int sum(int num)
{
if(num == 1)
return 1;
else
return num + sum(num - 1);
}
My problem starts when I try to solve the same problem using the following recursive definition:
"The sum of 1 to N is the sum of 1 to N/2 plus the sum of N/2 + 1 to N".
I tried the following but I'm stuck in an infinite loop...
public int sum(int max, int base)
{
if(max == base)
return base;
else
return max/2 + sum(max/2 - 1, 1) + max + sum(max-1, max/2 + 1);
}
I can't seem to find a way forward...
You are close, try something like this
#Test
public void recursive(){
int number = 20;
System.out.println(sum(0, number));
System.out.println(sum(0, number/2));
System.out.println(sum(number/2 +1, number));
Assert.assertThat(sum(0, number), is(sum(0, number/2) + sum(number/2 +1, number)));
}
private int sum(int origin, int end) {
if(origin == end)
return end;
return origin + sum(origin+1, end);
}
Related
I want to implement a recursive method that finds the sum of x consecutive integers, starting from a starting number and ending with an end number.
For example, if start = 0 and end = 3, the method returns 6 (0+1+2+3). I tried to come up with the right code but I'm new to recursion and I couldn't find the right base case.
public static int summation(int start, int end) {
if (start == end) {
return 0;
}
else {
return summation(end, end - 1);
}
}
This works but make sure that start is less than end.
public static int summation(int start, int end) {
if(start < end) return start + summation(start + 1, end);
else return end;
}
If you want to use the method to calculate sum between start and end even if start > end, then use this code:
public static int summation(int start, int end) {
if(start < end) return start + summation(start + 1, end);
else if(start > end) {
start += end;
end = start - end;
start -= end;
return summation(start, end);
}
else return end;
}
If recursion is not compulsory, you can use the formula for sum of Arithmetic Progression which you learn in HighSchool Algebra.
Formula for Sum of an AP is
S = n/2 * (2a + (n-1) * d)
In your case as you have to find the sum of consequetive terms, this formula simplifies to:
S = n/2 * (2a + n -1 )
Here, a is the starting term and n is the x consequetive integers from start to end.
public long sum(int start, int end) {
int n = end - start + 1;
return n/2 * (2L * start + n - 1);
}
Works even if start and end are negative. Just make sure start < end.
Recursion is a terrible approach here. Let's apply the method Gauss used in elementary school, the sum of the numbers 1 to n is found by taking of half of n multiplied by n + 1. Like,
private static long sumN(int n) {
return ((1L + n) * n) / 2;
}
Then you can use that to find summation like
private static long summation(int start, int end) {
return sumN(end) - sumN(start);
}
No recursion (or iteration) required.
I had a test exam in java, that almost no one have succeeded in this question and I can't figure out the solution.
The question was like this:
Find the sum of an integer last and first number. For example 1234-->5, 137-->8, 4-->8. You are only allowed to use recursion and no helper function"
I tried various things. Here is my last attempt:
public static int sumOfFirstandLastdigits(int number)
{
int lastdigit=sumOfFirstandLastdigits(number/10);
if(number/10==0)
{
return number%10;
}
return lastdigit+sumOfFirstandLastdigits(number%10);
}
Assuming the input is supposed to be non-negative:
//If n < 0, return first digit of -n
//Otherwise, return sum of first and last digits of n
int sumLastAndFirstDigit(int n) {
if (n < -9)
return sumLastAndFirstDigit(-(-n/10));
if (n <= 0)
return -n;
if (n < 10)
return n+n;
return n%10 + sumLastAndFirstDigit(-(n/10));
}
You can do this by overloading the method and passing the last digit as a second parameter to keep track of it through the recursion without changing the value (AKA Default Parameter):
public static void main(String[] args) {
System.out.println(sumDigits(3891901));
System.out.println(sumDigits(1234));
System.out.println(sumDigits(5678));
}
private static int sumDigits(int i) {
return sumDigits(i, i % 10);
}
private static int sumDigits(int i, int j) {
if (i / 10 == 0) {
return i % 10 + j;
}
return sumDigits(i / 10, j);
}
Output:
4
5
13
This thread on default parameters might help learn more as well.
Found a solution using String, not sure it's the best :
public int sumLastAndFirstDigit(Integer firstDigit, int number) {
String numberAsString = String.valueOf(number);
//Set the first digit
if(firstDigit == null) {
firstDigit = Integer.valueOf(numberAsString.substring(0,1));
//If there is only one digit in number for the first loop, then return 2 x firstDigit
if(numberAsString.length() == 1) {
return 2 * firstDigit;
}
}
//Remove the first digit to create the new number
String newNumberAsString = numberAsString.substring(1);
Integer newNumber = Integer.valueOf(newNumberAsString);
if(newNumberAsString.length() == 1) {
//When it's the last digit, sum first and last
return firstDigit + newNumber;
}
return sumLastAndFirstDigit(firstDigit, newNumber);
}
Then do :
sumLastAndFirstDigit(null,1234);
sumLastAndFirstDigit(null,137);
sumLastAndFirstDigit(null,4);
Use the sign as a flag to recognize the initial call. Only works with positive numbers, of course.
public static int sum(int value){
if(value > 0)
// initial call
return value % 10 + sum(-value);
else
// recursive call
return -value < 10 ? -value : sum(value / 10);
}
This are the 2 different solutions my professor suggested, although he said no helper (the first one is without an helper).
public static int sumFirstAndLast2(int num) {
if (num < 10 )
return num+num;
return sumFirstAndLast2(num/10) - num%100/10 + num%10;
}
public static int sumFirstAndLast(int num) {
if ( num < 10 )
return num+num;
return sumFirstAndLastHelper(num,true);
}
private static int sumFirstAndLastHelper(int num, boolean isLast) {
if ( isLast )
return num%10 + sumFirstAndLastHelper(num/10,false);
if ( num < 10 )
return num;
return sumFirstAndLastHelper(num/10,false);
}
For a programming assigment:
Create a recursive method in java that for example for n = 5 returns
1
.2
..3
...4
....5
...4
..3
.2
1
(let the point be spaces or tabs)this has been quite a headache im just started this course so im in beginner level and so far i have this
public String Esc(int n){
if (n <= 1)
return ""+n;
else
return n + "\n" + Esc(n - 1) + "\n" + n;
}
that returns
5
4
3
2
1
2
3
4
5
so im not even close and im still missing the spaces problem
thanks for helping
What you need is to do what you were doing, except backward. The way I found to do it was to basically have a counter going UP to the number n instead of going DOWN from n to 1.
Like this:
public static String esc(int n) {
return esc(1, n); // start at 1, go to n
}
// i counts from 1 to n and then stops at n
public static String esc(int i, int n) {
if (i == n) {
return getDots(i - 1) + i; // base case
}
else {
return getDots(i - 1) + i + "\n" + esc(i + 1, n) + "\n" + getDots(i - 1) + i;
}
}
// this method just generates n number of dots for the spacing
public static String getDots(int n) {
String dots = "";
for (int i = 0; i < n; i++) {
dots += ".";
}
return dots;
}
public static void main(String[] args) {
System.out.println(esc(5)); // call the function
}
So you can see that I recursively call the function using esc(i + 1, n) instead of n - 1. I'm counting i up by 1 each time until I reach n.
As for the use of the getDots method: The dots in front of each of the number happens to be that number subtract 1. So whenever the number is displayed (which is i), just display i - 1 dots in front of it.
Output:
1
.2
..3
...4
....5
...4
..3
.2
1
Shortest and easiest:
Demo: Press Start
Code ( first call set m to zero - see in the demo):
public static String Esc(int n, int m){
m = m + 1;
String s = "";
for ( int i= 0; i< (m-1); i++ ) s += '.';
if (n == m) return s + m;
return s + m + "\n" + Esc(n,m) + "\n" + s + m;
}
And even shorter:
public static String Esc(int n, int m) {
String s = "";
for (int i= 0; i< (m); i++) s += '.';
return n == m+1 ? s+(m+1) : s+(m+1)+"\n"+ Esc(n,m+1) +"\n"+s+(m+1);
}
And Even Shorter and without a for loop!! Demo: Press Start
public static String Esc(int n, int m) {
String s = new String(new char[m]).replace("\0", ".");
return n == m+1 ? s+(m+1) : s+(m+1)+"\n"+ Esc(n,m+1) +"\n"+s+(m+1);
}
Usage:
Esc(5, 0);
The trick is to use an accumulator.
class Test {
public static String esc(int n, String accum) {
if(n == 1) {
return accum;
}
int nMinusOne = n -1;
return esc(nMinusOne, nMinusOne + "\n" + accum + "\n" + nMinusOne);
}
public static String esc(int n) {
return esc(n, "" + n);
}
public static void main(String args[]) {
System.out.println(esc(5));
}
}
Here is one way to do it.
You pass in your value n twice. The reason is that you use n1 to print from 1 to n, and you then use n2 to print from n to 1. You also pass in a boolean flag that you make true once you switch the printing order.
Further more, you use n2 to reverse the value of n1 when printing such that:
n1 = 5, print 1
n1 = 4, print 2
// ....
This is done by the formula n2 + 1 - n1 as demonstrated bellow.
Since you said in the comments that you cannot use loops, I made the printing of dots into another recursive function.
Here is the result:
public static void printDots(int val, int condition) {
if(val < condition - 1) {
System.out.print(".");
printDots(val + 1, condition);
}
}
public static void Esc(int n1, int n2, boolean reverse) {
int val = (n2 + 1 - n1); // this gives 1 for n, 2 for n-1, 3 for n-2 etc.
if (n1 > 1 && !reverse) { // print from 1 to n
printDots(0, val); // print dots
System.out.println(val);
Esc(n1 - 1, n2, reverse);
} else if (n1 <= n2) { // print from n to 1
reverse = true;
printDots(0, val); // print dots
System.out.println(val);
Esc(n1 + 1, n2, reverse);
}
}
public static void main(String args[]) {
Esc(5, 5, false);
}
If you want to use the exact method signature you stated in your question, you can wrap the method I gave you above inside your method:
void Esc(int n) {
Esc(5, 5, false);
}
And then call Esc(5) from your main(). You can name the methods the same because java supports method overloading
Here is a running example
Output:
1
.2
..3
...4
....5
...4
..3
.2
1
public class Assignment {
private static int top;
public static void main(String[] args) {
top = 5;
recurse("", 1);
}
public static void recurse(String dots, int value) {
System.out.println(dots + value);
if (value == top) return;
recurse(dots + '.', value + 1);
System.out.println(dots + value);
}
}
It executes like this:
recurse("", 1) {
1 print 1
recurse(".", 2) {
.2 print .2
recurse("..", 3) {
..3 print ..3
recurse("...", 4) {
...4 print ...4
recurse("....", 5) {
....5 print ....5
return
}
...4 print ...4
}
..3 print ..3
}
.2 print .2
}
1 print 1
}
Now run it in the debugger to learn how it actually works.
I've having some trouble with recursion. At the moment, this code gives me an error message "missing return statement". Any way to get this working the way I want it to? I want it to calculate for xn and then return "count" when n reaches zero.
public class Question6p2 {
public static void main(String[] args){
int n = -6;
int x = 2;
int count = x;
power2(n, x, count);
System.out.println(power2(n, x, count));
}
public static int power2(int n, int x, int count){
if (n != 0){
if (n>0){
count = count * x;
n = n - 1;
}
else if (n<0) {
count = count * -x;
n = n + 1;
}
power2(n, x, count);
}
else if (n == 0){
return count;
}
}
}
Maybe I'm coming about this all wrong. Anyone care to help?
Currently, you have this statement:
power2(n, x, count);
... which ignores the result completely. In that branch, we never return anything from the method call. I suspect these two issues are linked.
I suspect you just want:
return power2(n, x, count);
Currently you are getting an error about not having a return statement because your return statement is within an if statement, so if that if statement doesn't run you will not return anything which is a problem.
Also I think you are going about recursion fundamentally wrong, as you are never calling back to your method recursively.
What you probably want to do within your power method is to accept n as the number of time to call your method, then lower it by 1 with each recursion. Then on every recursion multiply x by the original value.
Here is what I mean:
public static double power2(int n, int x,int xOriginal){
if(n == 0){
return 1;
}
if(n < 0){
return 1 / power2(n*-1, x, x);
}
if(n <= 1){
return x;
}
return power2(n -1, x * xOriginal, xOriginal);
}
Edit: Works with negative n now.
There are a few things wrong with your algorithm:
What does it mean to have a negative exponent?
You should understand that x-n can be written 1 / xn. This is not what was reflected in your algorithm.
All possible cases
There are 4 basic cases when calculating exponents.
There is any value x0 = 1.
Any x1 = x
Any negative exponent x-n = 1 / xn
Any positive exponent greater than one: xn where n > 1
Your algorithm should return 1 when x has an exponent of zero. Return x when the exponent is 1 or recursively call the algorithm when n > 1.
In the special case where n < 0 (ie you have a negative exponent) You can simply return the reciprocal 1 / method() as long as you change the sign of n before calling the method.
The line:
else if (n < 0){
n = -n;
return(1 / power2(n, x, count));
}
Checks for negative exponents, and returns 1 / xn Take note that the sign of n changed here, and now this is operating like any other method call with positive exponents.
public class TestCode {
public static void main(String[] args){
int n = 4;
int x = 5;
double count = x;
System.out.println(power2(n, x, count));
}
public static double power2(int n, int x, double count){
if (n == 0)
return 1;
else{
if (n > 1){
count = count * x;
n = n - 1;
}
else if (n < 0){
n = -n;
return(1 / power2(n, x, count));
}
else if (n == 1) {
return count;
}
return power2(n, x, count);
}
}
}
I need to write a recursive method to compute the following series:
m(i) = 1/3 + 2/5 + 3/7 + 4/9 + 5/11 + 6/13 + .... + i/(2i + 1)
Then I need to write a program that displays m(i) for i = 1,2,....10.
I understand the basic idea of recursion I had done 2 programs so far, one for factorials and one for a Fibonacci number sequence. This problem has me stumped.
This is what I have so far.
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(m(i));
}
}
public static double m(int i) {
if (i == 1)
return 1;
else
return ???;
}
First, it looks like your base case is off - that should be 1/3 (the first number in the series).
For your else, you should return the next step down added to the current step. Given your series, the current step is i/(2i + 1).
public static double m(int i) {
if (i == 1) {
// Base case is 1 - return the first number in the series
return 1/3;
} else {
// Get the current step (ie the current iteration of m(i))
double curStep = i / (2.0 * i + 1.0);
// Return the current step plus the next step down
return curStep + m(i - 1);
}
}
Does it need to be recursive? if not, a simple for loop will do the trick.
double sum = 0;
for(int x = 0; x < i; x++)
{
sum += x / (2.0 * x + 1);
}
return sum;
If it must be recursive, you need to start by properly identifying the base case. In this situation, your base case could be either 0 or 1. Examples:
Base case is 0:
public static double m(int i)
{
if(i==0)
return 0;
else
{
double sum = i/(2.0 * i + 1);
return sum + m(i-1);
}
}
Base case is 1:
public static double m(int i)
{
if(i==1)
return 1.0/3.0;
else
{
double sum = i/(2.0 * i + 1);
return sum + m(i-1);
}
}