Created
October 13, 2017 07:28
-
-
Save inabahare/fda544cb3d34f66217c2ca50a44ea61a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace PrimeFactorisatorInator { | |
class Program { | |
static void Main(string[] args) { | |
while (true) { | |
App (); | |
} | |
} | |
static void App () { | |
Console.Write ("Indtast et heltal mellem 2 og {0} der skal deles op i primtal: ", ulong.MaxValue); | |
string userInput = Console.ReadLine (); | |
Console.WriteLine ("Udregner heltal, vent venligst"); | |
Console.WriteLine (); | |
ulong userNumber = Convert.ToUInt64 (userInput); | |
// TODO: Check for numbers less than 2 | |
// The list containing the prime numbers | |
var primes = new List<ulong> (); | |
// Run the factorizer program | |
PrimeFactorizer (userNumber, ref primes); | |
if (primes.Count == 1) { // If the number is a prime number, the function with return a list of length 1 | |
Console.WriteLine ("Tallet {0} er et primtal!", userNumber); | |
} else { | |
Console.WriteLine ("Primtalsfaktorene er: "); | |
foreach (int p in primes) | |
Console.Write (p + " "); | |
} | |
Console.WriteLine ("\n----------------------------\n"); | |
} | |
/// <summary> | |
/// Will return a list of all the prime numbers that the number "n" can be divided with | |
/// </summary> | |
/// <param name="n"></param> | |
/// <returns>List of primes that when multiplied will </returns> | |
static void PrimeFactorizer (ulong n, ref List<ulong> primes) { | |
// Go through all the even divisors (which will always be 2) | |
CheckFactors (ref n, 2, ref primes); | |
// Go through all the odd divisors | |
for (ulong i = 3; i <= n; i += 2) | |
CheckFactors (ref n, i, ref primes); | |
// If the above checks fails, it means the number is a prime number | |
if (n > 2) | |
primes.Add (n); | |
} | |
/// <summary> | |
/// This function will check for divisors on a number and add it to a list of primes | |
/// </summary> | |
/// <param name="currentNumber">Number to check divisors on</param> | |
/// <param name="divisor">The divisor to check with</param> | |
/// <param name="primes">The list to add the prime numbers to</param> | |
static void CheckFactors (ref ulong currentNumber, ulong divisor, ref List<ulong> primes) { | |
while (currentNumber % divisor == 0) { // Go through all divisions with the divisor | |
primes.Add (divisor); // Add the divisor to the list of primes | |
currentNumber /= divisor; // Divide with the current prime number | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment