Prime Factors In C#

int a, b; Console.WriteLine(“Please enter your integer: “); a = int.Parse(Console.ReadLine()); for (b = 2; a > 1; b++) if (a % b == 0) { int x = 0; while (a % b == 0) { a /= b; x++; } Console.WriteLine($”{b} is a prime factor {x} times!”); } Console.WriteLine(“Th-Th-Th-Th-Th-… That’s all, folks!”);

Finding prime numbers with the Sieve of Eratosthenes (Originally: Is there a better way to prepare this array?)

Your method of finding primes, by comparing every single element of the array with every possible factor is hideously inefficient. You can improve it immensely by doing a Sieve of Eratosthenes over the entire array at once. Besides doing far fewer comparisons, it also uses addition rather than division. Division is way slower.

Calculating phi(k) for 1

This can be done with Memory complexity O(Sqrt(N)) and CPU complexity O(N * Log(Log(N))) with an optimized windowed Sieve of Eratosthenes, as implemented in the code example below. As no language was specified and as I do not know Python, I have implemented it in VB.net, however I can convert it to C# if you … Read more

Fast Prime Number Generation in Clojure

Here’s another approach that celebrates Clojure’s Java interop. This takes 374ms on a 2.4 Ghz Core 2 Duo (running single-threaded). I let the efficient Miller-Rabin implementation in Java’s BigInteger#isProbablePrime deal with the primality check. (def certainty 5) (defn prime? [n] (.isProbablePrime (BigInteger/valueOf n) certainty)) (concat [2] (take 10001 (filter prime? (take-nth 2 (range 1 Integer/MAX_VALUE))))) … Read more