Problem 3 showcases the use of functions, a while loop, and a call to the Math library.
using System; class Program { // Function that checks whether a number is prime static bool isPrime(long n) { int i; for (i=2;i<=Math.Sqrt(n);i++) { if (n%i==0) return false; } return true; } // Function that returns the next prime after a given number static long nextPrime(long n) { n++; while (!isPrime (n)) { n++; } return n; } // Function that returns the largest prime factor of a number static long LargestPrimeFactor(long n) { long i=2; while (!isPrime (n)) { if (n%i==0){ n = n/i; } else { i=nextPrime(i); } } return n; } static void Main(string[] args) { Console.WriteLine("{0}", LargestPrimeFactor(600851475143)); Console.ReadKey(); } }
No comments:
Post a Comment