An Interesting Program

I recently came across a very interesting mathematical problem. Here it is:

An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021…
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression:
d1 x d10 x d100 d1000 x d10000 x d100000 x d1000000
 
Simply put, the problem says make a fraction which reads 0(point)1,2,3,4,5,6,7,8,9,10,11… And then find the values of the digits at the 1st,10th,100th,1000th,10000th,100000th and 1000000th positions and multiply them to get the result.

Tough enough? Well its not quite so hard as you might think.

I made use of something I learned recently, known as a “stringstream”. It is nothing but a stream which inputs data as bytes and gives data corresponding to the datatype to which it is outputted. The solution to the above problem should make the functionality of the stringstream very clear:

#include<iostream>
#include<sstream> //Header file for stringstream

using namespace std;

int main()
{

stringstream ss; //A stringstream ss declared

ss.clear(); //Clears the data in the stringstream i.e. a data flush.

for(long i=1;i<=1000000;i++) // Max place is 10^6 so I loop till there
ss<<i;    //Push the integer bytes into the stream

string temp;

ss>>temp;   //Store the data in the stringstream in the temp string.

//Here the data of type long is implicitly converted to the
//string datatype i.e. the stringstream converts the data
//based on which datatype we are storing it in
//We use the string access operator i.e.[] to access the digits
//which we want at the corresponding values given
//These values are in their ASCII form so we subtract character constant
//'0' to get their absolute integer form
//After all, each digit is a value from 0 to 9.

long ans = 1;

for(long i=1;i<=1000000;i*=10) ans *= (temp[i] - '0');

cout<<ans<<endl;

//The product value is stored in a long variable which is then output
//to the user

system("pause");

return 0;
}

This should make the functionality and awesomeness of the stringstream quite clear. And the best part is that the solution is absolutely correct AND the program is highly efficient.

Thus in just about 20 lines of code I have managed to solve a problem which could have taken twice the size. Once the use of the stringstream is understood, this solution should come naturally to anyone.

Happy Coding!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s