Created
January 29, 2021 07:00
-
-
Save yuchiki/cc8ff15b4589eb90dfd5c51db1eed699 to your computer and use it in GitHub Desktop.
factorize
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; | |
using System.Collections.Generic; | |
using System.Linq; | |
const int N = 120; | |
var kvpString = factorize(N).Select(kvp => $"{kvp.Key}: {kvp.Value}"); | |
Console.WriteLine($"[{String.Join(", ", kvpString)}]"); | |
Multiset<int> factorize(int n) | |
{ | |
var factors = new Multiset<int>(); | |
for (var divisor = 2; divisor * divisor <= n; divisor++) | |
{ | |
while (n % divisor == 0) | |
{ | |
n /= divisor; | |
factors.Push(divisor); | |
} | |
} | |
if (n != 1) factors.Push(n); | |
return factors; | |
} | |
class Multiset<T> : IEnumerable<KeyValuePair<T, int>> | |
{ | |
private SortedDictionary<T, int> dictionary = new(); | |
public int this[T key] => dictionary.ContainsKey(key) ? dictionary[key] : 0; | |
public void Push(T value) | |
{ | |
if (dictionary.ContainsKey(value)) | |
{ | |
dictionary[value]++; | |
} | |
else | |
{ | |
dictionary[value] = 1; | |
} | |
} | |
public IEnumerator<KeyValuePair<T, int>> GetEnumerator() => dictionary.GetEnumerator(); | |
IEnumerator IEnumerable.GetEnumerator() => dictionary.GetEnumerator(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment