wu :: forums (http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi)
riddles >> cs >> USE OF atoi() function
(Message started by: syashid on Oct 2nd, 2011, 7:42am)

Title: USE OF atoi() function
Post by syashid on Oct 2nd, 2011, 7:42am
plz explain how to divide a number by 3 using only atoi() . also explain this function .how does it works.

Title: Re: USE OF atoi() function
Post by Grimbal on Oct 3rd, 2011, 1:39am
For "how does it work", just google "man atoi" and read the 1st link.

For example:
  char *str = "123";
  int n = atoi(str);
returns the integer 123 in n.

I don't see any way to divide an integer by 3 where atoi would be of some help.

You could convert the integer to a string in base 3, drop the last digit and re-convert the string to an integer, but you can't use atoi, it only does base 10.

Title: Re: USE OF atoi() function
Post by SMQ on Oct 3rd, 2011, 5:43am
Here's a simple -- if not very efficient -- implementation of atoi in case you want to search for a way to use it to divide by 3:

int atoi(const char * p) {
 int n;

 n = 0;
 while (*p >= 48 && *p <= 57) {
   n = n*10 + *p - 48;
   ++p;
 }

 return n;
}

--SMQ

Title: Re: USE OF atoi() function
Post by syashid on Oct 3rd, 2011, 8:41am
actually it has been asked in adobe. so a liitle help w'll b good

Title: Re: USE OF atoi() function
Post by Grimbal on Oct 3rd, 2011, 10:03am
What language are we talking about?

Title: Re: USE OF atoi() function
Post by websharer on Jan 6th, 2012, 5:10pm

on 10/03/11 at 10:03:30, Grimbal wrote:
What language are we talking about?

It's C++.

Title: Re: USE OF atoi() function
Post by TenaliRaman on Jan 6th, 2012, 10:54pm

on 01/06/12 at 17:10:46, websharer wrote:
It's C++.

are you sure its atoi and not itoa?

Title: Re: USE OF atoi() function
Post by Stefan Kneifel on Feb 2nd, 2012, 12:25pm
Maybe this way:


Code:
#include <stdio.h>
#include <stdlib.h>

int  main   (int argc, char** argv)
{
unsigned long x, y;
char c[16];

while (--argc)
{
 x = y = strtoul(*++argv, 0, 0);

 x = (x << 4) + y;
 x = (x << 4) + y;
 x = (x << 4) + y;

 sprintf (c, "%lu0", x);

 x = atoi(c) + y;

 x >>= 17;

 printf ("%lu / 3 = %lu\n", y, x);
}

return EXIT_SUCCESS;
}


Works up to 49152 / 3 = 16384. However, I think a simple division would be faster ;)

Title: Re: USE OF atoi() function
Post by SMQ on Feb 3rd, 2012, 5:16am
??? atoi isn't doing any division in that algorithm.  The two lines

sprintf (c, "%lu0", x);
x = atoi(c) + y;

are equivalent to x = x*10 + y;.  You're multiplying by 43691 = ({[(16 + 1)*16 + 1]*16 + 1}*10 + 1) then dividing by 131072, and if atoi can be said to be doing anything it's multiplying by 10.  The only division happens in the x >>= 17 step.

--SMQ



Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board