Fast integer input function in C

There can be few problems on online judges with large input data. Using traditional funcitons like scanf() for taking input would not work in such cases. So a function for taking faster inputs does effect final result.

Here is a function that reduces execution time in taking inputs of integeral numbers.

int get_num()
{
	int num = 0;
	char c = getchar_unlocked();
	while(!(c>='0' && c<='9'))
		c = getchar_unlocked();
	while(c>='0' && c<='9')
	{
		num = (num<<3) + (num<<1) + c -'0';
		c = getchar_unlocked();
	}
	return num;
}

How it works?

getchar_unlocked() is the function in C that takes inputs of character. It is much much faster in taking an input compared to scanf().

Coming to the functioning of function, c is a character variable and num is integer variable in which input number will be taken. Initially taking ‘c’ and checking if it lies in values between ‘0’ and ‘9’(It checks in ASCII order). Once you find the value of ‘c’ in the range, it gets into second while loop. Here, num value is changing the every time. It is indeed multiplied by 10, when everytime the while loop is repeated. Finally while loop breaks when c is some other character other than integral digit(in general will be a space or ‘\n’).

Atlast it returns the given input number. But this function is only for +ve integers. We can make a function for taking numbers including -ve numbers also.

It goes this way..

int get_num()
{
	int num = 0;
	char c = getchar_unlocked();
	int flag = 0;
	while(!((c>='0' & c<='9') || c == '-'))
		c=getchar_unlocked();
	if(c == '-')
	{
		flag = 1;
		c=getchar_unlocked();
	}
	while(c>='0' && c<='9')
	{
		num = (num<<1)+(num<<3)+c-'0';
		c=getchar_unlocked();
	}
	if(flag==0)
		return num;
	else
		return -1*num;
}

There is another function using fread() which takes much faster input.. you can read about that here.. FAST_I/O

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