Counting the Factors of a Number

By definition, a factor is one of two or more positive numbers that when multiplied together produce a given product.  For example, given the integer 24, the count of factors 8.

The below algorithm tests the range of numbers from 1 to a given integer.  If the given interger divided by the current number returns a remainder of 0, then the current number is a factor of the given integer.

 

public int GetFactorsCount(int i)
{
    return Enumerable.Range(1, i).Count(x => i % x == 0);
}

 

Get the source control, including unit tests: GetFactorsCount.zip (9.43 kb)


Getting All Factors for a Number

By definition, a factor is one of two or more positive numbers that when multiplied together produce a given product.  For example, given the integer 24, the factors are [1, 2, 3, 4, 6, 8, 12, 24].

The below algorithm tests the range of numbers from 1 to a given integer.  If the given integer divided by the current number returns a remainder of 0, then the current number is a factor of the given integer.

public List<int> GetFactors(int i)
{
    return Enumerable.Range(1, i).Where(x => i % x == 0).ToList();
}

 

Get the source control, including unit tests: GetFactors.zip (9.85 kb)


Testing LINQ Statements Using LINQPad

The other day I was needing a way to test some LINQ statements from an application which rebuilds a database while performing some calculations.  The rebuilding process is just shy of 24 hours.

Besides, there have been numerous other times in which I needed to test LINQ statements.

Troubleshooting LINQ can be difficult at times due to it deferred execution - the statement is executed as the last possible moment.  I wanted a tool similar to SQL Management Studio in which I could run LINQ queries against a database.  Thus, I stumbled upon (actually, it wasn't very hard to find) LINQPad.

Since, finding it, LINQPad has allowed me to test my queries prior to implementation in the application.  Therefore, I can better predict the result instead of waiting through a long process and/or waiting for QA to troubleshoot.

LINQPad allows the user to run C#, VB.NET, F# and SQL statements/expressions against the database - very flexible and extremely helpful.  LINQPad's flexibility allows the connection's data context to be LINQ to SQL, Entity Framework and WCF (OData).

Take a look at LINQPad at www.linqpad.net.