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?
One thing you can do is avoid checking even numbers after 2, since they will never be prime.
So, check 2 and then declare your loop as such:
Re: stopping at
sqrt(n)– this is an effective technique for determining whether a given number is prime, since anynthat dividesxwherex > sqrt(n)also dividesn/xwhich is necessarily less thansqrt(n). But a number may have prime factors larger than its own square root (for example, 1002 = 2 * 3 * 167).That said, you could implement some kind of recursive solution where, for all prime factors
pofnsuch thatp < sqrt(n), you also calculate the prime factors ofn / p. My gut feeling is that this will decrease the running time of your algorithm in general, but might increase it for small values ofn.Edit: if you’re interested in getting into more sophisticated techniques, the Wikipedia page on Integer Factorization links to all kinds of algorithms.