#1
06.01.2016 um 13:56 UhrDie zwei for-Schleifen zur Berechnung der Summe der Teiler ist genial! Wie bist du darauf gekommen? Ich hab auch eine Lösung geschrieben, welche aber im Vergleich zu deiner extrem langsam ist..

C# :: Aufgabe #88 :: Lösung #2
using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; namespace trainYourProgrammer { class MainClass { private static int[] CalcSigma(int limit) { //Summe der Teiler für jede Zahl <= limit int[] result = new int[limit + 1]; for (int i = 2; i <= limit; i++) { result [i] = 1; } for (int i = 2; i * 2 <= limit; i++) { for (int j = 2 * i; j <= limit; j += i) { result [j] += i; } } return result; } private static List<List<int>> SocialNumbers(int limit) { List<List<int>> result = new List<List<int>> (); int[] sigma = CalcSigma (limit); for (int i = 2; i <= limit; i++) { List<int> chain = new List<int> (5); int tmp = i; while (tmp > 0 && tmp <= limit && !chain.Contains(tmp)) { chain.Add (tmp); tmp = sigma [tmp]; } if (chain.Count > 2 && tmp == chain [0]) { //mache >2 zu == 2 für befreundete Zahlen bzw. == 1 für vollkommene Zahlen result.Add (chain); } if (tmp == chain [0] || tmp == 0 || tmp > limit) { foreach (int j in chain) { //eine Zahl kann nicht in 2 verschiedenen Ketten vorkommen sigma [j] = 0; } } } return result; } public static void Main(string[] args) { const int limit = (int)1e7; Stopwatch sw = Stopwatch.StartNew (); List<List<int>> numbers = SocialNumbers (limit); foreach (List<int> chain in numbers) { Console.WriteLine (String.Join (", ", chain)); } sw.Stop (); Console.WriteLine ("\nbenötigte Zeit: " + sw.ElapsedMilliseconds/1000.0 + " s"); } } }
Kommentare:
Robi
Punkte: 390
10 Lösungen
6 Kommentare
eulerscheZhl
Punkte: 5230
110 Aufgaben
76 Lösungen
64 Kommentare