w3resource

Java: Multiply two integers without using multiplication, division, bitwise operators, and loops


Multiply Without Operators

Write a Java program to multiply two integers without multiplication, division, bitwise operators, and loops.

Sample Solution:

Java Code:

import java.util.*;
public class solution {	
  public static int multiply_two_nums(int a, int b) { 
          
        /* 0 multiplied with anything gives 0 */
        if (b == 0) 
            return 0; 
      
        if (b > 0) 
            return (a + multiply_two_nums(a, b - 1)); 
            
        if (b < 0) 
            return -multiply_two_nums(a, -b); 
              
        return -1; 
    } 
 
   public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Input first integer: ");
        int num1 = scan.nextInt();
       System.out.print("Input second integer: ");
        int num2 = scan.nextInt();
        scan.close(); 
       System.out.println("Multiply of two integers: "+multiply_two_nums(num1, num2));		
		}
 }

Sample Output:

 Input first integer:  5
Input second integer:  25
Multiply of two integers: 125

Flowchart:

Flowchart: Multiply two integers without using multiplication, division, bitwise operators, and loops.

For more Practice: Solve these Related Problems:

  • Write a Java program to multiply two integers recursively using only addition and subtraction.
  • Write a Java program to implement multiplication by simulating the doubling and halving method recursively.
  • Write a Java program to multiply numbers without loops or arithmetic operators, using recursion to simulate repeated addition.
  • Write a Java program to perform multiplication by converting the integers to strings and processing digit by digit.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find the square root of a number using Babylonian method.
Next: Write a Java program to calculate power of a number without using multiplication and division operators.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.