Product of two numbers using recursion java

Product of two numbers using recursion java

By : Ashlee Bennett
Date : November 21 2020, 11:01 PM
hope this fix your issue You are correct in your explanation of how the method works, but remember, since this is recursive, it ends up returning the total of all returns. Let me explain: The first recursion returns 3 + product(3, 1). However, your program does not know what product(3, 1) is yet, so it must continue before returning. The second recursion (product(3, 1)) returns 3 + product(3, 0). Again, your program must continue the recursion to find product(3, 0). The third and final recursion returns 0, as you said, but the FINAL answer goes back to the first recursion's answer, 3 + product(3, 1). We know that product(3, 1) = 3 + product(3, 0), and product(3, 0) = 0. So product(3, 2) = 3 + 3 + 0, which is 6. It appears in your answer that you were expecting only to receive the final recursion for an answer, but because of your return statement, it is a combination of the three.
code :

Share : facebook icon twitter icon
Getting product and quotient of 2 numbers using recursion without using the * and / operators

Getting product and quotient of 2 numbers using recursion without using the * and / operators

By : KingPenguin
Date : March 29 2020, 07:55 AM
like below fixes the issue I am trying to learn programming and I am on the phase of learning recursion. Before this, I have successfully solve the problem but using loops. Right now, since recursion is quite interesting to me, I was wondering if I could convert the loop into a recursive method. I have done my attempts but I've been getting a sort of infinite computation whatsoever. , Try this:
code :
public static int recursiveProduct(int a, int b) {
  if (b == 0) {
    return 0;
  } else {
    return a + recursiveProduct(a,--b);
Recursion related: Product of two numbers

Recursion related: Product of two numbers

By : Hesham Fouad
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I thought this would be relatively easy but running it, gives wrong result. It may be the initialization of the result variable but I cant seem to be able to modify the code such as to be correct. Here is my progress so far. , better solution *here*
code :
public static int product(int n1, int n2) 
              if (n2 > 1) 
                  n1 += product(n1,n2-1) ; 
                 return n1; 
Sum of numbers using recursion java

Sum of numbers using recursion java

By : Mark Tate
Date : March 29 2020, 07:55 AM
hope this fix your issue The main problem is that you are always recursing when sum != n. When the sum gets bigger than n, you never stop, hence the StackOverflowError This means we need to add a check and terminate when the sum gets bigger:
code :
public static void test_2(String path, int sum, int n) {
    if (sum == n) {
    } else if (sum < n) { // <-- only recurse if the sum is less than the target
        test_2(path+"1 ", sum + 1, n);
        test_2(path+"2 ", sum + 2, n);
        test_2(path+"3 ", sum + 3, n);
        test_2(path+"4 ", sum + 4, n);
1 1 1 1 
1 1 2 
1 2 1 
1 3 
2 1 1 
2 2 
3 1 
Product of two arrays using recursion Java

Product of two arrays using recursion Java

By : jaladi thirumala nag
Date : March 29 2020, 07:55 AM
Hope that helps The auxiliary method is a good suggestion, but with a different method signature than that you listed in your code.
Reason being is that you need to keep track of the index less than n, then your base-case for the recursion is when that index is greater than n.
code :
import java.util.Arrays;

public class Product {

    // auxiliary method
    private static void _arrayProd(int[] v1, int[] v2, int[] result, int n, int i) {
        if(i < n){
            result[i] = v1[i] * v2[i];
             _arrayProd(v1, v2, result, n, i+1);

    public static int[] arrayProd(int[] v1, int[] v2, int n) {
        int[] result = null;
        if(n >= 0){
            result = new int[n];
            _arrayProd(v1, v2, result, n, 0);
        return result;

    public static void main(String [] args) {
        int[] v1 = {1, 2, 3, 4, 5};
        int[] v2 = {2, 4, 6, 8};
        int n = 3;

        int[] v3 = arrayProd(v1, v2, n);

understanding recursion for dot product in java

understanding recursion for dot product in java

By : Samcro
Date : March 29 2020, 07:55 AM
Any of those help Ok so hoping you have tried it before this is one possible way to code it.
code :
public class ArrayExample {
public static void main (String[] args) {
    int[] a = {2,2,2,2};
    int[] b = {2,2,2,2};
    int n = a.length;
    int result = recurseSum(a, b, n-1);

public static int recurseSum(int[] a, int[] b, int n){
    if(n == 0)
        return a[0]*b[0];
        return (a[n] * b[n]) + recurseSum(a,b,n-1);
Related Posts Related Posts :
  • ExecutorService and OutOfMemoryError: unable to create new native thread while using Executor
  • Java Security Manager completely disable reflection
  • Placement of Thread Content. How do you know what goes inside of the thread, and what doesn't?
  • can not search for txt files android 6.0
  • Monitor program using semaphore does not work as expected in java
  • A way to define / implement failover ldap servers in java code
  • How to save embedded object in POST call using Spring Data Rest
  • Methods in test in parallel way
  • What would be the best way to implement to check if the Post has been liked by the User using JPA and MySQL?
  • GCM unregister causing the application to crash
  • Test configuration annotations in separate annotation
  • How to catch third party console log using log4j
  • Spring Boot: Conditional on database type
  • Java: Loading data from a file located under project folder fails
  • Epson epos sdk receipt alignment issue
  • Java Comparable: helper methods for isLessThan, isGreaterThan, isEqualTo
  • How to find the native method from the JVM source code?
  • Insert datetime string from java in MySQL
  • Regex look ahead to seperate string into tokens
  • How the java de-compiler get to know the variable or object names?
  • Java generics "capture of ?"
  • Specify the default value of the JSONP callback in spring using jackson?
  • Digital Signature created in C# doesn't match in Java verification
  • How to push down project, filter, aggregation to TableScan in Calcite
  • Java/SQL find duplicates
  • Getting a null error trying to add objects into an arraylist (simple piece of code)
  • JDBC query returning zero when using simple arithmetic operations and alias even though the data in table is not zero
  • incompatible type while adding value to Map
  • Openshift Build Failure - Failed to read artifact descriptor
  • updating neo4j database using java program
  • how to save an image to disk and retrive it with java/jsp
  • How to verify kerberos token?
  • String to byte array conversion varies from windows and ubuntu
  • Custom MavenResourcesFiltering hard to implement?
  • TestNG XML file failed to invoke/create the XSSFWorkbook
  • BigDecimal issue with long and lat
  • I am new to JavaFX. I want help on how to make a TreeView node Draggable and Droppable
  • Microservices and Messaging: Message Content
  • How to move an email service into a thread?
  • Reading a .csv file faster than reading same file compressed as .gz
  • How to change the json response fields to user defined fields in java?
  • Retrofit: Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for CustomClass
  • Basic Authentication failed in Windows server 2012 Using Java
  • Avoid Transaction rollback in Spring
  • Transition between right - up, left - down, down - left etc. (JAVA game LWJGL keylistener)
  • How to setup a common classpath for all dependencies inside a maven project?
  • How is Mockito.mock better that using new while writing Junit tests?
  • In apache http client, how to keep the Content-Type in a StringBody as empty or null?
  • SQuirreL Configure: could not initial class org.apache.phoenix.jdbc.PhoenixDriver
  • ResponseEntity decode UTF-8
  • Time difference gives wrong value
  • How to read in and split a string of numbers separated by whitespace and forward slash
  • InvocationTargetException in javafx
  • method reference vs lambda expression
  • Scaling issue in BigDecimal(java) for exponential notation
  • What is causing my app to crash in this program? - Android Studio
  • My method returning an Optional cannot be used in a functional-like way
  • Dangling meta character '*' near index 6
  • How to parse a string in java to get only some parts of it
  • How to replace special character using regex in Mule Dataweave transformation?
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com