Problem 1 (Text book, problem 4, programming projects, chapter 2, page 158) Weir
ID: 3749942 • Letter: P
Question
Problem 1 (Text book, problem 4, programming projects, chapter 2, page 158) Weird multiplication For this assignment, you will be implementing the so-called "Russian Peasant" or "Ancient Egyptian method for multiplication. It looks a little odd, but just think of it as an algorithm, a recipe for doing multiplication in a way other than what you learned in grade school. The algorithm is as follows. If A and B are the 2 integers (only integers) to be multiplied, we repeatedly multiply A by 2 and divide B by 2, until B cannot be divided any further, that is, until its value becomes 0 (remember, this is integer division). During each step, whenever B is an odd number, we add the corresponding A value to the product we are generating. In the end, the sum of the A values that had corresponding odd B values is the product. Get it? Here is an example If the two integers to be multiplied are 34 and 19, the operations would be: Comment 34 68 136 272 544 19 Add A to the product, B is odd 9 Add A to the product, B is odd 4 Ignore this A value, B is even 2 Ignore this A value, B is evern 1 Add A to the product, B is odd Sum up all the A values that had odd B values and you get: 34+68+544- 646>Final product. (a) Part 1: Write a program to find the product of two integers (b) Part 2: Modify your program so that it repeatedly asks whether you want to find another product.Explanation / Answer
#include<iostream>
using namespace std;
int main(){
cout<<"Hello to Weird multiplication calculator"; // Commented section is for part 2 of the question.
char ch= 'y';
int sum=0;
int n1;
int n2;
//do{
cout<<endl<<"Enter number 1: ";
cin>>n1;
cout<<endl<<"Enter number 2: ";
cin>>n2;
while(n2){
if(n2%2)
{
sum+=n1;
}
n1*=2;
n2/=2;
}
cout<<endl<<"Product = "<<sum;
cout<<endl<<endl<<"Do you want to enter new numbers ?";
cout<<"Do you want to enter more ?(y/n)";
cin>>ch;
//}
//while(ch=='y'||ch=='Y');
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.