Can you help me optimize this code for finding factors of a number? I'm brushing up on my math progr

Posted by Sergio Tapia on Stack Overflow See other posts from Stack Overflow or by Sergio Tapia
Published on 2010-03-13T15:26:03Z Indexed on 2010/03/13 15:35 UTC
Read the original article Hit count: 319

Filed under:
|
|

I've never really bothered with math programming, but today I've decided to give it a shot.

Here's my code and it's working as intended:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PrimeFactorization
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            List<int> primeFactors = FindPrimeFactors(Convert.ToInt32(txtNumber.Text));
            primeFactors.Sort();
            for (int i = 0; i < primeFactors.Count; i++)
            {
                listBoxFoundNumbers.Items.Add(primeFactors[i]);
            }            
        }

        private List<int> FindPrimeFactors(int number)
        {
            List<int> factors = new List<int>();
            factors.Add(1);
            factors.Add(number);

            for (int i = 2; i < number; i++)
            {

                if (number % i == 0)
                {
                    int holder = number / i;
                    //If the number is in the list, don't add it again.
                    if (!factors.Contains(i))
                    {
                        factors.Add(i);
                    }
                    //If the number is in the list, don't add it again.
                    if (!factors.Contains(holder))
                    {
                        factors.Add(holder);
                    }
                }            
            }

            return factors;
        }
    }
}

The only problem I can see with my code is that it will iterate through to the bitter end, even though there will definitely not be any factors.

For example, imagine I wrote in 35. My loop will go up to 35 and check 24,25,26,27...etc. Not very good.

What do you recommend?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET