Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to find the last digit of an int in C++

Tags:

c++

I want to try writing my own BigInt Class so I am wondering what would be the most efficient way to find the last digit of a number in C, especially for an input that would be an extremely large int.

like image 549
dddddd Avatar asked Jun 08 '10 21:06

dddddd


People also ask

How do you determine the last digit in any number?

Finding the last digit of a number is the same as finding the remainder when this number is divided by 10. In general, the last digit of a power in base n is its remainder upon division by n. So, for decimal numbers, we compute mod 10 to find the last digit, mod 100 to find the last two digits, etc.

How do you print the last digit of an array?

To get the last digit of each number, you should use the remainder % operator. For two numbers m and n , m % n returns the remainder of m divided by n . Beware of the negative numbers you might need to use Math. abs() as well.


2 Answers

lastDigit = number % 10;
like image 104
protobuf Avatar answered Sep 21 '22 13:09

protobuf


I'm assuming that your BigInt uses a base-256 implementation, but this would work equally well for base-65536 or even bigger bases.

Start with a simple example: BigInt(2828) would be stored as 11*256 + 12. Now BigInt(2828) % 10 = (11*256+12) % 10 = ((11 % 10)*(256 % 10) + 12 % 10)) % 10 = (256 % 10 + 2) % 10 = (6+2) % 10 = 8.

The two basic rules that you'll be applying are (a+b)%10 = (a%10 + b%10) % 10, and (a*b)%10 = (a%10 * b%10) % 10. As it happens, not only is 256 % 10 == 6, but (256^N) % 10 = (6^N) % 10 = 6. This enormously simplifies your LastDigit() function.

So, again assuming a BigInt B represented as a sequence d_N..d_0 with base 256. Then B % 10 is (6*sum(d_i % 10) - 5 * (d_0 % 10)) % 10. Each term in the summation is at most 9, obviously. Hence you can trivially sum (ULONG_MAX/6) base-256 digits without overflowing, and the same still applies to base-65536 and base-4294967296

like image 37
MSalters Avatar answered Sep 20 '22 13:09

MSalters