Q:

Write a script to add two 30-digit numbers and print the result. This is not as easy as it might sound at first, because integer types may not be able to store a value this large

0

 Write a script to add two 30-digit numbers and print the result. This is not as easy as it might sound at first, because integer types may not be able to store a value this large. One way to handle large integers is to store them in vectors, where each element in the vector stores a digit of the integer. Your script should initialize two 30-digit integers, storing each in a vector, and then add these integers, also storing the result in a vector. Create the original numbers using the randi function. Hint: add 2 numbers on paper first, and pay attention to what you do! 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Ch5Ex40.m

num1 = randi([0,9],1,10);

num2 = randi([0,9],1,10);

num1plusnum2 = zeros(1,11);

carry = 0;

for i = 10:-1:1

 sumit = num1(i) + num2(i) + carry;

 if sumit <= 9

 num1plusnum2(i+1) = sumit;

 carry = 0;

 else

 num1plusnum2(i+1) = rem(sumit,10);

 carry = 1;

 end

end

num1plusnum2(1) = carry; 

 

fprintf(' %s\n',num2str(num1))

fprintf(' %s\n', num2str(num2))

fprintf('%s\n', num2str(num1plusnum2))

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now