/// <summary> /// Finds greatest prime factor. /// </summary> public static long Q003(long n) { // n > 1; List <long> factors = new List <long>(); factors.Add(n); long sqrt = (long)Math.Floor(Math.Sqrt(n)); for (long i = 2; i <= sqrt; i++) { if (n % i == 0) { factors.Add(i); factors.Add(n / i); } } factors.Sort(); for (int i = factors.Count - 1; i >= 0; i--) { if (NumberTheory.IsPrime(factors[i])) { return(factors[i]); } } return(-1); }
public void TestIsPrime_Int64() { Assert.That(NumberTheory.IsPrime(2), Is.True); Assert.That(NumberTheory.IsPrime(3), Is.True); Assert.That(NumberTheory.IsPrime(4), Is.False); Assert.That(NumberTheory.IsPrime(5), Is.True); Assert.That(NumberTheory.IsPrime(10), Is.False); Assert.That(NumberTheory.IsPrime(17), Is.True); Assert.That(NumberTheory.IsPrime(641), Is.True); Assert.That(NumberTheory.IsPrime((long)(int.MaxValue) + 1), Is.False); foreach (var i in NumberTheory.PrimesLessThan1000) { Assert.That(NumberTheory.IsPrime(i), Is.True); } }
public void TestIsPrime() { Assert.That(NumberTheory.IsPrime(2), Is.True); Assert.That(NumberTheory.IsPrime(3), Is.True); Assert.That(NumberTheory.IsPrime(4), Is.False); Assert.That(NumberTheory.IsPrime(5), Is.True); Assert.That(NumberTheory.IsPrime(10), Is.False); Assert.That(NumberTheory.IsPrime(17), Is.True); Assert.That(NumberTheory.IsPrime(641), Is.True); //unchecked //{ // Assert.That(NumberTheory.IsPrime(int.MaxValue + 1), Is.True); //} foreach (var i in NumberTheory.PrimesLessThan1000) { Assert.That(NumberTheory.IsPrime(i), Is.True); } }
public void TestPrintPrimes() { int count = 0; for (int i = 2; i < 104800; i++) { if (NumberTheory.IsPrime(i)) { Console.Write(i + " "); count++; if (count % 10 == 0) { Console.WriteLine(); } } } Console.WriteLine(); Console.WriteLine(count); }