- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathTrialDivisionFactorizer.cs
executable file
·23 lines (21 loc) · 851 Bytes
/
TrialDivisionFactorizer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
usingSystem;
usingSystem.Linq;
namespaceAlgorithms.Numeric.Factorization;
/// <summary>
/// Factors number using trial division algorithm.
/// </summary>
publicclassTrialDivisionFactorizer:IFactorizer
{
/// <summary>
/// Finds the smallest non trivial factor (i.e.: 1 < factor <= sqrt(<paramref name="n" />)) of a given number or returns false if it's prime.
/// </summary>
/// <param name="n">Integer to factor.</param>
/// <param name="factor">Found factor.</param>
/// <returns><see langword="true" /> if factor is found, <see langword="false" /> if <paramref name="n" /> is prime.</returns>
publicboolTryFactor(intn,outintfactor)
{
n=Math.Abs(n);
factor=Enumerable.Range(2,(int)Math.Sqrt(n)-1).FirstOrDefault(i =>n%i==0);
returnfactor!=0;
}
}