Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write an m-file to add two 30-digit numbers and print the results. This is not a

ID: 3701595 • Letter: W

Question

Write an m-file to add two 30-digit numbers and print the results. 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 built in function randi.m. Hint: Add two large numbers on paper first and pay attention to the algorithm!

Explanation / Answer

a=randi([0,9],30,1); %initialising the two numbers
b=randi([0,9],30,1); %randi function returns a vector of size 30x1 with random digits in [0,9]

carry=0;
sum=zeros(31,1);   
for i = 30:-1:1
sum(i+1)=mod((a(i)+b(i)+carry),10); %store the sum value in the respective position
carry=fix((a(i)+b(i)+carry)/10); %carry forward the carry value for next addition
end;

sum(1)=carry; % store the final carry value

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote