For this problem, instead of int –> use uint- unsigned integers that range from 0

Question: For this problem, instead of int –> use uint- unsigned integers that range from 0 to uint.MaxValue. Do not use the checked keyword.

Your new job as a Computational Physicist involves calculations using very large integers. However, some of the results are incorrect. For example, when adding very large positive integers, sometimes the results are wrong. After consulting with a Computer Science professor for a large fee :). you have determined in some cases the results are too large to fit into an integer.

  1. Write a static method called addBigNumbers that adds two integers and returns the results. If the result is too large to fit into uint.MaxValue, throw an error. Hint: How can you tell if the result is too large to fit? The result will always be <= unit.MaxValue even if it is too large to fit!
  2. Test the method in the main routine using values (i) that fit and (ii) values that result in a sum that is too large to fit. Make sure that the main routine doesn’t crash by adding try and catch blocks. To help, use the following code in main

For(unit i=unit.maxValue/2 – 3;i<unit.MaxValue/2 +3; i++)

{

try

{

Console.WriteLine(i+” + “+i);
uint res=addBigNumbers(i,i);
   Console.WriteLine(“………………..”);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}

}

Solution:

Result:

Code:

using System;


namespace addBigNumbersConsole
{
class Program
{
static void Main(string[] args)
{
for(uint i=uint.MaxValue/2-3;i<uint.MaxValue/2+3;i++)
{
try
{
Console.WriteLine(i+” + “+i);
uint res=addBigNumbers(i,i);
  
if (res == 0 || res==2)
{
throw new System.ArgumentException(“Values are higher than the maximum capacity of uint”);
}
else
{
Console.WriteLine(res);
}
Console.WriteLine(“………………..”);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}

  
}

Console.ReadLine();
}

static uint addBigNumbers(uint i, uint j)
{
uint sum = i + j;
return sum;
}

}
}

Leave a Reply

Your email address will not be published. Required fields are marked *