Thread: Finding # of digits in an integer

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    10

    Finding # of digits in an integer

    Please help with the problem described in the title.
    I'm writing a little thing to find prime numbers.
    I'm looking for a really fast method.
    I'm a very early beginner.
    I have thought of dividing the int by 10 until it equals 0.
    I have thought of converting the int into a string and finding length.
    Is there a faster way?

    Thanks very much in advance.

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    ceiling ( log(num) / log(10) )

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    10
    Quote Originally Posted by Thantos
    ceiling ( log(num) / log(10) )
    Thanks.
    Is this method fast?
    Is there a faster one?
    Would this method work if x is a multiple of 10?

  4. #4
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Is this method fast?
    Depends
    Is there a faster one?
    Probably
    Would this method work if x is a multiple of 10?
    Try it and see

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > I have thought of dividing the int by 10 until it equals 0.
    Would work

    > I have thought of converting the int into a string and finding length.
    Also would work.

    > Is there a faster way?
    Consider
    Code:
    while ( x >= 10000 ) { x /= 10000 ; count += 4; }
    while ( x >= 10 ) { x /= 10 ; count += 1; }
    Also, are you generating a whole series of numbers in a for loop, and trying to find the length of each?
    Say for ( i = 1 ; i < 100000000 ; i++ ) kind of thing?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  2. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  3. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 02:24 PM
  4. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  5. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 10:43 AM