Results 1 to 5 of 5

Thread: [octave/matlab] I want to add the number of digits in a number

  1. #1
    Join Date
    May 2008
    Beans
    65
    Distro
    Xubuntu 12.04 Precise Pangolin

    [octave/matlab] I want to add the number of digits in a number

    Hello!

    I'm calculating Fibonacci numbers and I want to count the number of digits for the nth. My code at the moment looks like this:

    Code:
    Fn = FnMinus1 + FnMinus2;
    DigitCount = columns(isdigit(int2str(Fn)));
    Fn being the nth Fib#

    My way is fairly longwinded (feel free to skip this paragraph if you know your stuff): 'int2str' converts it to a string, 'isdigit' creates a row vector with 1 for every digit (i.e. 012345678 or 9) in a different column. Then 'columns' counts the number of columns.

    This works fine for 3/4/5 digits but Octave goes dead when I ask it to count 1000 digits. I think it's probably my chain of functions that's slowing me down. Anyone know a better way of doing it?

    It is for a Project Euler problem.

  2. #2
    Join Date
    Aug 2006
    Location
    Madrid, Spain
    Beans
    299
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [octave/matlab] I want to add the number of digits in a number

    Simple if you know your basic math, just take ceil(log10(n+1)).
    May the Source be with you.

  3. #3
    Join Date
    May 2007
    Beans
    23

    Re: [octave/matlab] I want to add the number of digits in a number

    Why do you need isdigit? Since you use int2str, the string will only contain whole numbers without any decimals, can't you just use columns directly on the string like this?
    Code:
    DigitCount = columns((int2str(Fn));
    The math solution is probably way faster, and its more elegant.
    Last edited by hofsmo; September 15th, 2009 at 10:20 PM.

  4. #4
    Join Date
    May 2008
    Beans
    65
    Distro
    Xubuntu 12.04 Precise Pangolin

    Re: [octave/matlab] I want to add the number of digits in a number

    if you know your basic math
    Oh. Apparently I don't. I've never come across that property of log_10 before.

    Thanks

  5. #5
    Join Date
    May 2008
    Beans
    65
    Distro
    Xubuntu 12.04 Precise Pangolin

    Re: [octave/matlab] I want to add the number of digits in a number

    can't you just use columns directly on the string like this?
    Yes I can. Didn't know that.

    Still runs slowly using the string conversions though.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •