last digit

simple

#1

how to know the last digit of a 1000 digit long number …
also can we also store such a large number in c++…
if yes, how…


#2

first calculate the length of the number, and den use the “percentile” method of calculating the last digit.

fo example:

no= 46484881454

here, no of digits= 11

so
lastdigit= no%pow(10,11)
where 10 is constant and 11 is the no of digits in the given number.
pow is the function in mths.h library file…

hope you lyk the answer.
thanks


#3

and we can store large digits in c…

use ‘double’, ‘long int’, etc etcc…


#4

Hello,

It depends on how this 1000 digit number is given to you…

If it is given in input, you can read it as a string and you are done :slight_smile:

If it is the result of a series of calculations that get more and more complex and possibly lead to overflow, then the best way is to use an array to hold the digits and perform grade-school arithmetics like you were taught when you were young :slight_smile:

It will also obviously depend on the kind of operations being performed, but, for multiplications, you can read a post I made to solve the problem Small Factorials.

There, I briefly explain how to handle very large numbers using an array, you can find it here and I hope you find it helpful!

Best regards,

Bruno


#5

u mean 2 say i shud store it in a string and then calculate its length … and then proceed.


#6

hi @callam2pm well i dont think you can store this big number as a “number” in c++.

The obvious solution is to use String. String is a sequence of characters. Unlike ints and longs which have a paticular predefined range, strings dont have any such restriction(Except for the memory limit itself!).

So, here is the c++ code you might be looking for.

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
   char num[1001];
   cin>>num;

   // if the number is exactly of 1000 digits always then to get the last digit simply:
  // cout<<"the last digit is:"<<num[999];

 // if the number isnt of 1000 digits exactly then u must find its length first:

 int length = strlen(num); //this function returns the length of the string
 cout<<"the last digit is: "<<num[length-1];
 return 0;
}

Hope this helps :slight_smile:


#7

As I said…It depends on how the number is given to you, read my answer above


#8

u can also store it in strng format. bt dere will be a prblm. u cant use mathematical operations on string format.
so its better to use long int , double… etc etc


#9

long int, double and etc etc as you say, can never, ever store a number which is 1000 digits long…So a string should be used… Plus, if only the last digit is needed, such operation can be done easily on a string.


#10

@sailesharya no you cannot use these inbuilt datatypes they can not store such a long number.
Go to this page and scroll down a bit you will see a table having range of various variables like char int, long etc. that will make thing clear for you :slight_smile: