Created
October 12, 2017 07:36
-
-
Save inabahare/2f576a2d3850b3f4d4e6d13f174fa2cc 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 der skal deles op i primtal: "); | |
string userInput = Console.ReadLine (); | |
Console.WriteLine ("Udregner heltal, vent venligst"); | |
Console.WriteLine (); | |
long userNumber = Convert.ToInt64 (userInput); | |
// The list containing the prime numbers | |
var primes = new List<long> (); | |
PrimeFactorizer (ref 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 (ref long n, ref List<long> 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 (int 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 long currentNumber, int divisor, ref List<long> 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