Write a program to multiply two numbers without using the '*' operator.
Example 1:
Input:a=7,b=8
Output:a=56
Approach 1: Iterative
Java
public class MultiplicationTwoNumber {public static void main(String[] args) {int a = 7;int b = 8;int mul = multiplicationTwoNum(a, b);System.out.println("Multiplication is " + mul);}private static int multiplicationTwoNum(int a, int b) {int m = 0;if (b == 0 || a == 0)return 0;if (b > 0) {while (b > 0) {m += a;b--;}return m;}if (b < 0) {while (b < 0) {m += a;b++;}return -m;}return m;}}
C++
#include <bits/stdc++.h>using namespace std;//function to multiply two numbers//without using * operatorint multiplicationTwoNum(int a,int b){int mul=0;if(a==0||b==0)return mul;if(b>0){while (b>0){mul+=a;b--;}return mul;}if(b<0){while(b<0){mul+=a;b++;}return -mul;}return mul;}int main(){int a=7;int b=8;int multiply=multiplicationTwoNum(a, b);cout<<"Multiplication is ";cout<<multiply<<"\n";return 0;}
Approach 2: Recursive
Java
public class MultiplicationTwoNumber {public static void main(String[] args) {int a = 7;int b = 8;int mul = multiplicationTwoNum(a, b);System.out.println("Multiplication is " + mul);}private static int multiplicationTwoNum(int a, int b) {if (b == 0)return 0;if (b > 0) {return a + multiplicationTwoNum(a, b - 1);}if (b < 0) {return -multiplicationTwoNum(a, -b);}return 0;}}
C++
#include <bits/stdc++.h>using namespace std;//function to multiply two numbers//without using * operatorint multiplicationTwoNum(int a,int b){if(b==0)return 0;if(b>0)return a+multiplicationTwoNum(a,b-1);if(b<0)return -multiplicationTwoNum(a,-b);return 0;}int main(){int a=7;int b=8;int multiply=multiplicationTwoNum(a, b);cout<<"Multiplication is ";cout<<multiply<<"\n";return 0;}
No comments:
Post a Comment