Sunday, February 13, 2011

Best way to find all factors of a given number in C#

All numbers that divide evenly into x.

I put in 4 it returns: 4, 2, 1

edit: I know it sounds homeworky. I'm writing a little app to populate some product tables with semi random test data. Two of the properties are ItemMaximum and Item Multiplier. I need to make sure that the multiplier does not create an illogical situation where buying 1 more item would put the order over the maximum allowed. Thus the factors will give a list of valid values for my test data.

edit++: This is what I went with after all the help from everyone. Thanks again!

edit#: I wrote 3 different versions to see which I liked better and tested them against factoring small numbers and very large numbers. I'll paste the results.

static IEnumerable<int> GetFactors2(int n)
        {
            return from a in Enumerable.Range(1, n)
                          where n % a == 0
                          select a;                      
        }

        private IEnumerable<int> GetFactors3(int x)
        {            
            for (int factor = 1; factor * factor <= x; factor++)
            {
                if (x % factor == 0)
                {
                    yield return factor;
                    if (factor * factor != x)
                        yield return x / factor;
                }
            }
        }

        private IEnumerable<int> GetFactors1(int x)
        {
            int max = (int)Math.Ceiling(Math.Sqrt(x));
            for (int factor = 1; factor < max; factor++)
            {
                if(x % factor == 0)
                {
                    yield return factor;
                    if(factor != max)
                        yield return x / factor;
                }
            }
        }

In ticks. When factoring the number 20, 5 times each:

  • GetFactors1-5445881
  • GetFactors2-4308234
  • GetFactors3-2913659

When factoring the number 20000, 5 times each:

  • GetFactors1-5644457
  • GetFactors2-12117938
  • GetFactors3-3108182
  • pseudocode:

    • Loop from 1 to the square root of the number, call the index "i".
    • if number mod i is 0, add i and number / i to the list of factors.

    realocode:

    public List<int> Factor(int number) {
        List<int> factors = new List<int>();
        int max = (int)Math.Sqrt(number);  //round down
        for(int factor = 1; factor <= max; ++factor) { //test from 1 to the square root, or the int below it, inclusive.
            if(number % factor == 0) {
                factors.add(factor);
                if(factor != max) { // Don't add the square root twice!  Thanks Jon
                    factors.add(number/factor);
                }
            }
        }
        return factors;
    }
    

    As Jon Skeet mentioned, you could implement this as an IEnumerable<int> as well - use yield instead of adding to a list. The advantage with List<int> is that it could be sorted before return if required. Then again, you could get a sorted enumerator with a hybrid approach, yielding the first factor and storing the second one in each iteration of the loop, then yielding each value that was stored in reverse order.

    You will also want to do something to handle the case where a negative number passed into the function.

    Jon Skeet : One extra check to add - the above will add 2 twice :)
    Echostorm : Math.Sqrt returns a double. Also, that needs to be rounded up. Try using 20 as an example.
    Mark Ransom : Rather than taking the square root, you can restructure the loop: for(int factor = 1; factor*factor <= number; ++factor)
    Chris Marasti-Georg : True - and I would imagine there is a point past which performance would degrade for that, since you are calculating it on each loop? It is probably not as significant as other parts of the loop. Benchmarking would have to be performed, I suppose.
    Echostorm : cool idea Mark. you have to test against factor * factor != x when you're yielding tho.
  • Is this homework? If so, I'd rather walk you through you solving it than just give you an answer.

    Are you aware of the % (remainder) operator? If x % y == 0 then x is divisible by y. (Assuming 0 < y <= x)

    I'd personally implement this as a method returning an IEnumerable<int> using an iterator block, but that's relatively advanced if you're fairly new to C#.

    From Jon Skeet
  • Linq solution:

    IEnumerable<int> GetFactors(int n)
    {
      Debug.Assert(n >= 1);
      return from i in Enumerable.Range(1, n)
             where n % i == 0
             select i;
    }
    
    Chris Marasti-Georg : This is wrong - it only returns half of them.
    Jay Bazuzi : This only gets you the first 1/2 of factors. e.g., for 10, it would return 1 and 2, but not 5 and 10.
    Jon Skeet : Suggested change: Math.Sqrt will return a double, which won't work with Enumerable.Range. Also that won't return 4 - just 1 and 2.
  • As extension methods:

        public static bool Divides(this int potentialFactor, int i)
        {
            return i % potentialFactor == 0;
        }
    
        public static IEnumerable<int> Factors(this int i)
        {
            return from potentialFactor in Enumerable.Range(1, i)
                   where potentialFactor.Divides(i)
                   select potentialFactor;
        }
    

    Here's an example of usage:

            foreach (int i in 4.Factors())
            {
                Console.WriteLine(i);
            }
    

    Note that I have optimized for clarity, not for performance. For large values of i this algorithm can take a long time.

    From Jay Bazuzi
  • How big is x going to be?

    For small numbers, you can get away with a naive solution, but for larger x it would be useful to implement a better algorithm (Wikipedia describes some).

  • Here it is again, only counting to the square root, as others mentioned. I suppose that people are attracted to that idea if you're hoping to improve performance. I'd rather write elegant code first, and optimize for performance later, after testing my software.

    Still, for reference, here it is:

        public static bool Divides(this int potentialFactor, int i)
        {
            return i % potentialFactor == 0;
        }
    
        public static IEnumerable<int> Factors(this int i)
        {
            foreach (int result in from potentialFactor in Enumerable.Range(1, (int)Math.Sqrt(i))
                                   where potentialFactor.Divides(i)
                                   select potentialFactor)
            {
                yield return result;
                if (i / result != result)
                {
                    yield return i / result;
                }
            }
        }
    

    Not only is the result considerably less readable, but the factors come out of order this way, too.

    Chris Marasti-Georg : Why not just edit the old answer?
    Jay Bazuzi : Because they are two different answers, with differing merit.
    From Jay Bazuzi
  • Wouldn't it also make sense to start at 2 and head towards an upper limit value that's continuously being recalculated based on the number you've just checked? See N/i (where N is the Number you're trying to find the factor of and i is the current number to check...) Ideally, instead of mod, you would use a divide function that returns N/i as well as any remainder it might have. That way you're performing one divide operation to recreate your upper bound as well as the remainder you'll check for even division.

    Math.DivRem http://msdn.microsoft.com/en-us/library/wwc1t3y1.aspx

    From mspmsp
  • Another LINQ style and tying to keep the O(sqrt(n)) complexity

            static IEnumerable<int> GetFactors(int n)
            {
                Debug.Assert(n >= 1);
                var pairList = from i in Enumerable.Range(1, (int)(Math.Round(Math.Sqrt(n) + 1)))
                        where n % i == 0
                        select new { A = i, B = n / i };
    
                foreach(var pair in pairList)
                {
                    yield return pair.A;
                    yield return pair.B;
                }
    
    
            }
    
    From pablito
  • A bit late but the accepted answer does not give the correct results. (at least the 3 different answers does not give the results even if they run in similar time)

    I don't know why there is a limit set at the square root ? It's been a while since I did some math but it seems that we can only divide by two (maybe 3 for odd number to decrease a little bit the runtime?)

        public static IEnumerable<uint> getFactors(uint x)
        {
            uint max = x / 2;
            for (uint i = 1; i <= max; i++)
            {
                if (0 == (x % i))
                {
                    yield return i;
                }
            }
        }
    

Which is recommended: "static public" or "public static"

Hi,

If you have a class member that is static and public. Would you write "static public" or "public static"? I know they are the same. But is there some recommendation / best practice for writing this?

  • I personally would go with public static because it's more important that it's public than that it's static.

    And check this: http://checkstyle.sourceforge.net/config_modifier.html

    As well as this: http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html (These two links are for Java, but the concept is the same)

    Short version: "public static" is recommended and is far more common.

    From Epaga
  • "public static" is far more common, so you might want to go with that just to increase readability for programmers who never stumbled upon "static public".

  • see this question

    If you download the Microsoft StyleCop Visual Studio addin, it can validate your source code against the rules Microsoft use. It likes the access modifier to come first.

    From Mark Heath
  • When nothing else matters, go with consistency. In this case the rest of the world uses public static, so I'd go with that too just to avoid unnecessary surprise in those reading your code.

How to determine if XElement.Elements() contains a node with a specific name?

For example for the following XML

 <Order>
  <Phone>1254</Phone>
  <City>City1</City>
  <State>State</State>
 </Order>

I might want to find out whether the XElement contains "City" Node or not.

  • Just use the other overload for Elements.

    bool hasCity = OrderXml.Elements("City").Any();
    
    Daud : Thnx. This is the one I wanted.
    jcollum : Or use Descendants("MyNode").Any() if you don't care about where it is in the tree.
    From David B
  • It's been a while since I did XLinq, but here goes my WAG:

    from x in XDocument
    where x.Elements("City").Count > 0
    select x
    

    ;

How to enable buttons when scroll bar hits bottom with Win32?

I'm writing a license agreement dialog box with Win32 and I'm stumped. As usual with these things I want the "accept/don't accept" buttons to become enabled when the slider of the scroll bar of the richedit control hits bottom, but I can't find a way to get notified of that event. The earliest I've been able to learn about it is when the user releases the left mouse button.

Is there a way to do this?

Here's what I tried so far:

  • WM_VSCROLL and WM_LBUTTONUP in richedit's wndproc
  • EN_MSGFILTER notification in dlgproc (yes the filter mask is getting set)
  • WM_VSCROLL and WM_LBUTTONUP in dlgproc.
  • EN_VSCROLL notification in dlgproc

I got so desperate I tried polling but that didn't work either because apparently timer messages stop arriving while the mouse button is down on the slider. I tried both:

  • timer callback (to poll) in dlgproc
  • timer callback (to poll) in richedit's wndproc
  • You need to sub-class the edit box and intercept the messages to the edit box itself. Here's an artical on MSDN about subclassing controls.

    Skizz

    EDIT: Some code to demonstrate the scroll bar enabling a button:

    #include <windows.h>
    #include <richedit.h>
    
    LRESULT __stdcall RichEditSubclass
    (
      HWND window,
      UINT message,
      WPARAM w_param,
      LPARAM l_param
    )
    {
      HWND
        parent = reinterpret_cast <HWND> (GetWindowLong (window, GWL_HWNDPARENT));
    
      WNDPROC
        proc = reinterpret_cast <WNDPROC> (GetWindowLong (parent, GWL_USERDATA));
    
      switch (message)
      {
      case WM_VSCROLL:
        {
          SCROLLINFO
            scroll_info = 
            {
              sizeof scroll_info,
              SIF_ALL
            };
    
          GetScrollInfo (window, SB_VERT, &scroll_info);
    
          if (scroll_info.nPos + static_cast <int> (scroll_info.nPage) >= scroll_info.nMax ||
              scroll_info.nTrackPos + static_cast <int> (scroll_info.nPage) >= scroll_info.nMax)
          {
            HWND
              button = reinterpret_cast <HWND> (GetWindowLong (parent, 0));
    
            EnableWindow (button, TRUE);
          }
        }
        break;
      }
    
      return CallWindowProc (proc, window, message, w_param, l_param);
    }
    
    LRESULT __stdcall ApplicationWindowProc
    (
      HWND window,
      UINT message,
      WPARAM w_param,
      LPARAM l_param
    )
    {
      bool
        use_default_proc = false;
    
      LRESULT
        result = 0;
    
      switch (message)
      {
      case WM_CREATE:
        {
          CREATESTRUCT
            *creation_data = reinterpret_cast <CREATESTRUCT *> (l_param);
    
          RECT
            client;
    
          GetClientRect (window, &client);
    
          HWND
            child = CreateWindow (RICHEDIT_CLASS,
                                  TEXT ("The\nQuick\nBrown\nFox\nJumped\nOver\nThe\nLazy\nDog\nThe\nQuick\nBrown\nFox\nJumped\nOver\nThe\nLazy\nDog"),
                                  WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL | ES_DISABLENOSCROLL,
                                  0, 0, client.right, client.bottom - 30,
                                  window,
                                  0,
                                  creation_data->hInstance,
                                  0);
    
          SetWindowLong (window, GWL_USERDATA, GetWindowLong (child, GWL_WNDPROC));
          SetWindowLong (child, GWL_WNDPROC, reinterpret_cast <LONG> (RichEditSubclass));
          SetWindowLong (child, GWL_ID, 0);
    
          child = CreateWindow (TEXT ("BUTTON"), TEXT ("Go Ahead!"), WS_CHILD | WS_VISIBLE | WS_DISABLED, 0, client.bottom - 30, client.right, 30, window, 0, creation_data->hInstance, 0);
    
          SetWindowLong (window, 0, reinterpret_cast <LONG> (child));
          SetWindowLong (child, GWL_ID, 1);
        }
        break;
    
      case WM_COMMAND:
        if (HIWORD (w_param) == BN_CLICKED && LOWORD (w_param) == 1)
        {
          DestroyWindow (window);
        }
        break;
    
      default:
        use_default_proc = true;
        break;
      }
    
      return use_default_proc ? DefWindowProc (window, message, w_param, l_param) : result;
    }
    
    int __stdcall WinMain
    (
      HINSTANCE instance,
      HINSTANCE unused,
      LPSTR command_line,
      int show
    )
    {
      LoadLibrary (TEXT ("riched20.dll"));
    
      WNDCLASS
        window_class = 
        {
          0,
          ApplicationWindowProc,
          0,
          4,
          instance,
          0,
          LoadCursor (0, IDC_ARROW),
          reinterpret_cast <HBRUSH> (COLOR_BACKGROUND + 1),
          0,
          TEXT ("ApplicationWindowClass")
        };
    
      RegisterClass (&window_class);
    
      HWND
        window = CreateWindow (TEXT ("ApplicationWindowClass"),
                               TEXT ("Application"),
                               WS_VISIBLE | WS_OVERLAPPED | WS_SYSMENU,
                               CW_USEDEFAULT,
                               CW_USEDEFAULT,
                               400, 300, 0, 0,
                               instance,
                               0);
    
      MSG
        message;
    
      int
        success;
    
      while (success = GetMessage (&message, window, 0, 0))
      { 
        if (success == -1)
        {
          break;
        }
        else
        {
          TranslateMessage (&message);
          DispatchMessage (&message);
        }
      }
    
      return 0;
    }
    

    The above doesn't handle the user moving the cursor in the edit box.

    From Skizz
  • Even though it is possible, I don't think you should do it that way - the user will have no clue why the buttons are disabled. This can be very confusing, and confusing the user should be avoided at all costs ;-)

    That's why most license dialogs have radio buttons for accept/decline with decline enabled by default, so you actively have to enable accept.

    Ilya : Every license agreement i seen up to know have this feature.
    Treb : I doubt that. Anyway, my answer stays: Don't do it.
    Graeme Perrow : I wouldn't say every license agreement has it, in fact most I've seen don't. But I have seen some that do, so it certainly is possible.
    Treb : Yup, I've seen the answer above. It can be done, will edit my answer accordingly.
    From Treb
  • Skizz, I did subclass the richedit control and I did intercept messages that Windows sends to that control. I gave examples of that in my original post. For example, when I said that I had looked for WM_VSCROLL in the richedit's wndproc, it meant that I had substituted my own wndproc for the richedit's default wndproc and was intercepting its WM_VSCROLL message.

    Treb, I am trying to do this the conventional way. I'll l look at some more license agreement screens but I think most of them only enable "Accept" when you scroll to the bottom. (I may have been wrong about both buttons starting off disabled, but even if it's only the "accept" button that needs to become enabled, the technical issue is the same.)

    Skizz : The code I posted above works as required using VS2k5. The only real gotcha was that scroll bar position != scroll bar max when the thumb is at the bottom of the scroll bar. The correct test is scroll bar position + page size >= scroll bar max.
    : I don't think you understand the problem.
    : The problem is that as long as the user's finger is holding down the mouse button and the mouse cursor is on the slider, Windows doesn't send WM_VSCROLL to the controls's wndproc.
    From
  • Skizz, in reply to your code example, my original post said that I had already tried that. The first example I gave of things I had tried was this:

    "WM_VSCROLL and WM_LBUTTONUP in richedit's wndproc"

    That's what you're doing in your example -- responding to WM_VSCROLL in the control's wndproc. Once again -- I'm repeating myself -- I tried that already and it doesn't work for this purpose, because the operating system does not send WM_VSCROLL to the control's wndproc while the user is holding the mouse button down with the mouse cursor on the thumb. That's the problem.

    What's the point of telling me to try things that I already said I tried and found not to work?

    Skizz : It really does work! The code also tracks the ScrollInfo.nTrackPos which is updated even if the user has not let go of the mouse button!
    From
  • I would recommend starting up Spy++ and seeing which windows messages are getting sent to where.

    http://msdn.microsoft.com/en-us/library/aa264396(VS.60).aspx

    From jussij
  • Why not use the EM_GETTHUMB message. (Assuming Rich Edit 2.0 or later).

    If you are lucky this bottom position will match EM_GETLINECOUNT.

Do you know a free hosting for ClickOnce apps?

I am developing an application that will be open source, and i want this application to be updatable through ClickOnce (or similar), but i want to implement it from a free hosting, as i don't know the volume of downloads i will have. I would need something like sourceforge or codeplex,a hosting that allows me to see the version and in that case, alert the user that there is another newer version and download it.

  • As far as I see, you can use any web server to host ClickOnce packages. Because of that, using SourceForge could be good, because they do provide you with normal webspace.

    Also see this question for a bit more information about hosting ClickOnce applications on a normal web server like Apache (which, I believe, is used by SourceForge).

    From hangy
  • You'll probably have to add the following to your .htaccess file:

    AddType application/x-ms-application application
    AddType application/x-ms-manifest manifest
    AddType application/octet-stream deploy
    AddType application/vnd.ms-xpsdocument xps
    AddType application/xaml+xml xaml
    AddType application/x-ms-xbap xbap
    AddType application/x-silverlight-app xap
    

    Beyond that, there are no server side requirements for hosting ClickOnce or Silverlight 2.0 applications. (The last 4 types are those that add support for Silverlight).

    From TimothyP
  • In SourceForge the only thing you can do is upload the files, you cannot touch the htaccess, but i think this is not my problem at this moment. I think the only thing i need is a ftp, but i would like it to be a ftp related with open source world or software world. In any case, a free hosting with ftp.

    From netadictos

Custom Error Pages in JBoss

Hey all, This is my first question here!

I'm trying to setup custom error pages in my JBoss RESTful web service. I'm starting with the 400 error, so in my web.xml I've added

<error-page>
 <error-code>400</error-code>
 <location>/400.html</location>
</error-page>

and I've placed 400.html at the root of my war file (I've also tried placing it at the root of WEB-INF). Unfortunately, I keep getting 404's when I'm supposed to get 400's, presumably because JBoss can't seem to find 400.html. Any ideas what I'm doing wrong?

Might it be because my servlets are mapped to the root?

<servlet-mapping>
 <servlet-name>api</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

if so, what are the alternatives?

Thanks!

  • For posterity: I was able to finally get this working by redirecting errors to a page that Spring MVC had a controller for. The controller just returned a null ModelAndView. Because it was a RESTful service, I really didn't need to have any HTML emitted anyway.

Python file interface for strings

Is there a Python class that wraps the file interface (read, write etc.) around a string? I mean something like the stringstream classes in C++.

I was thinking of using it to redirect the output of print into a string, like this

sys.stdout = string_wrapper()
print "foo", "bar", "baz"
s = sys.stdout.to_string() #now s == "foo bar baz"

EDIT: This is a duplicate of How do I wrap a string in a file in Python?

  • Yes, there is StringIO:

    import StringIO
    import sys
    
    
    sys.stdout = StringIO.StringIO()
    print "foo", "bar", "baz"
    s = sys.stdout.getvalue()
    
    CAdaker : That's it. Thanks.
  • For better performance, note that you can also use cStringIO. But also note that this isn't very portable to python 3.