Stack overflow exception with recursion - java

I am trying to make a program which calculates double factorial (example - n=3, => (3!)! = 6! = 720) but i have some issues with recursion bottom and i have stack overflow exception.
public static long df(long n) {
if (n == 1) {
return 1;
} else {
return df(n * df(n - 1));
}
}
public static void main(String[] args) {
System.out.println(df(3));
}

You're encountering an infinite loop with df(n * df(n - 1));
n * df(n-1) will compute the factorial, and you're inadvertently feeding your answer back into the recursive method, causing it to go on forever
Change
return df(n * df(n - 1));
to
return n * df(n - 1);
and you should get the correct result for factorials
Once you have this working recursive factorial method, it becomes much easier to create a double factorial by just using df(df(3))

I think you should use mutual recursion with the help of factorial.
The general g-factorial function can compose factorial g times:
public static long gf(long n, long g) {
if (g == 1){
return fact(n);
}
return fact(gf(n, g - 1));
}
The specific double factorial can be gf(n, 2):
public static long df(long n) {
return gf(n, 2);
}
And the factorial helper function:
public static long fact(long n) {
if (n == 1) {
return 1;
} else {
return n * fact(n - 1);
}
}
Now test:
public static void main(String[] args) {
System.out.println(df(3));
}

We can do:
public static long factorial(long n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
public static long twice_factorial(long n) {
return factorial(factorial(n));
}
And, if needed, with some trickery turn this into a single method:
public static long twice_factorial(long n) {
return new Object() {
long factorial(long n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
long twice_factorial(long n) {
return factorial(factorial(n));
}
}.twice_factorial(n);
}
But this is a useless function as it's only good for n < 4 -- once we reach (4!)!, we exceed the limit of Java's long type:
(4!)! = 24! = 620,448,401,733,239,439,360,000
Java 'long' +max = 9,223,372,036,854,755,807
If you want this function to be useful, you might use a floating approximation equation instead. But calling approximate factorial again on an approximation probably doesn't make much sense. You'd want a floating approximation equation for the nested factorial value itself.
Or, we can switch to BigInteger:
import java.math.BigInteger;
public class Test {
public static BigInteger factorial(BigInteger n) {
return (n.compareTo(BigInteger.ONE) <= 0) ? n : n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
public static BigInteger twice_factorial(BigInteger n) {
return factorial(factorial(n));
}
public static void main(String[] args) {
System.out.println(twice_factorial(new BigInteger(args[0])));
}
}
USAGE
> java Test 4
620448401733239439360000
>
But this only gets to (7!)! before we get java.lang.StackOverflowError! If we want to go further, we need to dump the recursion and compute the factorial iteratively:
public static BigInteger factorial(BigInteger n) {
BigInteger result = BigInteger.ONE;
while (n.compareTo(BigInteger.ONE) > 0) {
result = result.multiply(n);
n = n.subtract(BigInteger.ONE);
}
return result;
}
USAGE
> java Test 8
34343594927610057460299569794488787548168370492599954077788679570543951730
56532019908409885347136320062629610912426681208933917127972031183174941649
96595241192401936325236835841309623900814542199431592985678608274776672087
95121782091782285081003034058936009374494731880192149398389083772042074284
01934242037338152135699611399400041646418675870467025785609383107424869450
...
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000
>

Firstly, define your factorial function:
Via Jupyter:
#include <iostream>
std::cout << "some output" << std::endl;
long fac(long n) {
if( n == 1)
return 1;
else
return n * fac((n-1));
}
And after define your function:
long double_fac(long n)
{
long step_one = fac(n);
return fac(step_one);
}
Factorielle-Algorythme

Related

How can I turn this code from long into BigInteger

It is a code that gets prime numbers, I have made it as efficient as I could, but the problem is that I can't transform it to BigInteger, as long can't hold that much information; here the code:
public class p3{
static long perfectNumber;
static long mersenne;
public static void main(String[] args) {
long p = 2;
while (true) {
if( p % 2 == 0&&p!=2){
p++;
}
else{
if (isPrime(p) == true) {
mersenne = (long) (Math.pow(2, p) - 1);
if (isPrime(mersenne) == true) {
perfectNumber = (long) Math.pow(2, (p - 1)) * mersenne;
System.out.println(perfectNumber);
}
}
p+=1;
}
}
}
private static boolean isPrime(long testPrime) {
for (long i = 3; i < Math.sqrt(testPrime); i += 2) {
if (testPrime % i == 0) {
return false;
}
}
return true;
}
}
I've tried to use BigInteger but code is not working, as I can't use
BigInteger exponents with pow
You don't need to. The exponents don't need to be nearly as large as the mersenne primes and perfect numbers. They can have their own independent isPrime() test. In fact, they need to be int, instead of long, to satisfy BigInteger.pow().
Below is what you asked for, but may not be what you want. I doubt you'll get more then one additional perfect number beyond your original code due to time constraints which is why #WJS is pushing you in a different direction.
import java.math.BigInteger;
public class p3 {
static BigInteger TWO = new BigInteger("2");
static BigInteger THREE = new BigInteger("3");
public static void main(String[] args) {
int p = 2;
while (true) {
if (isPrime(p)) {
BigInteger mersenne = TWO.pow(p).subtract(BigInteger.ONE);
if (isPrime(mersenne)) {
System.out.println(TWO.pow(p - 1).multiply(mersenne));
}
}
p += (p == 2) ? 1 : 2;
}
}
private static boolean isPrime(BigInteger number) {
if (number.mod(TWO).equals(BigInteger.ZERO)) {
return number.equals(TWO);
}
for (BigInteger i = THREE; number.compareTo(i.multiply(i)) >= 0; i = i.add(TWO)) {
if (number.mod(i).equals(BigInteger.ZERO)) {
return false;
}
}
return true;
}
private static boolean isPrime(int number) {
if (number % 2 == 0) {
return number == 2;
}
for (int i = 3; number >= i * i; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
OUTPUT
> java p3
6
28
496
8128
33550336
8589869056
137438691328
2305843008139952128
2658455991569831744654692615953842176
Your original code outputs 0 in place of the final (37 digit) number above. So the immediate issue really is that long can't hold enough information. But beyond this point, you simply can't calculate fast enough with the above algorithm.
If we do something simple-minded to my above code, like replace this line:
if (isPrime(mersenne)) {
with:
if (mersenne.isProbablePrime(10)) {
The code will spit out the first 20 perfect numbers before slowing to a crawl. Tune the certainty argument of isProbablePrime() as you see fit.

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);
}
}

e^x = 1 + x + x2/2! + x3/3! + x4/4! << e to the x power using java method

So. Hello smart ones. What am I doing wrong here? I just can't figure out what is wrong with this code. 10 points for whomever helps me.
I'm trying to use recursion to make a method for e^x. using the e^x = 1 + x + x2/2! + x3/3! + x4/4! + ... equation
public class tester {
public static double power(double x, int n) {
if (n == 0) {
return 1;
} else {
return x * power(x, n - 1);
}
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static double myexp(double x, int n) {
if (n == 0) {
return 1;
} else {
return (power(x, n) / factorial(n)) + myexp(x, n - 1);
}
}
public static void main(String[] args) {
System.out.println(myexp(x, n)); // unfortunately, increasing n value
// makes it go infinite.
}
}
So x is the x in e^x and n is the total value when up to nth term is added. So
for example, myexp(3,5) is going to be e^3 added up to 5th term. Thus, the higher the n is, the more accurate e^3 is going to be.
Your problem is the use of the "int" data type for the factorial method. More specifically, factorial numbers quickly become huge and the int data type is too small. For example, if you code:
public static void main(String[] args) {
System.out.println(factorial(50));
}
The output is 0 which is obviously wrong, hence your result of Infinity. Simply change the return type of factorial from intto double as follows:
public static double factorial(int n)
And then if you try:
public static void main(String[] args) {
System.out.println(myexp(1., 100));
}
You get 2.7182818284590455

What does the method prod() do in this Java program?

public class Prod {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
}
This is an exercise in the book I am stumped on. Why would the program not just recurse until the two numbers are equal and then return n ? Also, where it says,
int result = n * recurse;
How does it multiply int n by recurse which would be (int, int)? How can it multiply one integer by a set of two integers?
In what way am I misunderstanding this program?
EDIT: This is a different question because I am not using factorials
prod(x,y) is equivalent to y! when x=1.
If x is different from 1, then its doing recursive multiplication (y * (y- 1) * (y -2) .... ) until y = x.
Assuming y > x.
By the way, if x > y then prod() will crash.

How to write a function that can calculate power in Java. No loops

I've been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b) class... or method still can't distinguish the two am not so good with theory. So i wrote this..
public static void main(String[] args) {
int a = 2;
int b = 31;
System.out.println(Math.pow(a, b));
}
Then i wanted to make my own Math.pow without using loops i wanted it to look more simple than loops, like using some type of Repeat I made a lot of research till i came across the commons-lang3 package i tried using StringUtils.repeat
So far I think this is the Syntax:-
public static String repeat(String str, int repeat)
StringUtils.repeat("ab", 2);
The problem i've been facing the past 24hrs or more is that StringUtils.repeat(String str, int 2); repeats strings not out puts or numbers or calculations.
Is there anything i can do to overcome this or is there any other better approach to creating a function that calculates powers?
without using loops or Math.pow
This might be funny but it took me while to figure out that StringUtils.repeat only repeats strings this is how i tried to overcome it. incase it helps
public static int repeat(int cal, int repeat){
cal = 2+2;
int result = StringUtils.repeat(cal,2);
return result;
}
can i not use recursion maybe some thing like this
public static RepeatThis(String a)
{
System.out.println(a);
RepeatThis(a);
}
just trying to understand java in dept thanks for all your comments even if there were syntax errors as long as the logic was understood that was good for me :)
Another implementation with O(Log(n)) complexity
public static long pow(long base, long exp){
if(exp ==0){
return 1;
}
if(exp ==1){
return base;
}
if(exp % 2 == 0){
long half = pow(base, exp/2);
return half * half;
}else{
long half = pow(base, (exp -1)/2);
return base * half * half;
}
}
Try with recursion:
int pow(int base, int power){
if(power == 0) return 1;
return base * pow(base, --power);
}
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
This one handles negative exponential:
public static double pow(double base, int e) {
int inc;
if(e <= 0) {
base = 1.0 / base;
inc = 1;
}
else {
inc = -1;
}
return doPow(base, e, inc);
}
private static double doPow(double base, int e, int inc) {
if(e == 0) {
return 1;
}
return base * doPow(base, e + inc, inc);
}
I think in Production recursion just does not provide high end performance.
double power(double num, int exponent)
{
double value=1;
int Originalexpn=exponent;
double OriginalNumber=num;
if(exponent==0)
return value;
if(exponent<0)
{
num=1/num;
exponent=abs(exponent);
}
while(exponent>0)
{
value*=num;
--exponent;
}
cout << OriginalNumber << " Raised to " << Originalexpn << " is " << value << endl;
return value;
}
Use this code.
public int mypow(int a, int e){
if(e == 1) return a;
return a * mypow(a,e-1);
}
Sure, create your own recursive function:
public static int repeat(int base, int exp) {
if (exp == 1) {
return base;
}
return base * repeat(base, exp - 1);
}
Math.pow(a, b)
Math is the class, pow is the method, a and b are the parameters.
Here is a O(log(n)) code that calculates the power of a number. Algorithmic technique used is divide and conquer. It also accepts negative powers i.e., x^(-y)
import java.util.Scanner;
public class PowerOfANumber{
public static void main(String args[]){
float result=0, base;
int power;
PowerOfANumber calcPower = new PowerOfANumber();
/* Get the user input for the base and power */
Scanner input = new Scanner(System.in);
System.out.println("Enter the base");
base=input.nextFloat();
System.out.println("Enter the power");
power=input.nextInt();
result = calcPower.calculatePower(base,power);
System.out.println(base + "^" + power + " is " +result);
}
private float calculatePower(float x, int y){
float temporary;
/* Termination condition for recursion */
if(y==0)
return 1;
temporary=calculatePower(x,y/2);
/* Check if the power is even */
if(y%2==0)
return (temporary * temporary);
else{
if(y>0)
return (x * temporary * temporary);
else
return (temporary*temporary)/x;
}
}
}
Remembering the definition of the logarithm, this can be done with ln and exp if these functions are allowed. Works for any positive base and any real exponent (not necessarily integer):
x = 6.7^4.4
ln(x) = 4.4 * ln(6.7) = about 8.36
x = exp(8.36) = about 4312.5
You can read more here and also here. Java provides both ln and exp.
A recursive method would be the easiest for this :
int power(int base, int exp) {
if (exp != 1) {
return (base * power(base, exp - 1));
} else {
return base;
}
}
where base is the number and exp is the exponenet

Categories

Resources