Advertisement
AlFas

PrimeR code

Apr 29th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.53 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Runtime.InteropServices;
  11. using System.Windows.Forms;
  12. using System.IO;
  13.  
  14. namespace PrimeR
  15. {
  16.     public partial class MainForm : Form
  17.     {
  18.         int primesNo = 100;
  19.         int totalProgress, stage1progress, stage2progress, stage3progress, stage4progress, stage5progress;
  20.         int stage1progressMax, stage2progressMax, stage3progressMax, stage4progressMax, stage5progressMax = 1;
  21.         IntPtr thisProcess = new IntPtr(Process.GetCurrentProcess().Id);
  22.         BackgroundWorker calculate = new BackgroundWorker();
  23.         bool doneCalculating = true;
  24.        
  25.         public MainForm()
  26.         {
  27.             InitializeComponent();
  28.             calculate.DoWork += Calculate;
  29.             calculate.WorkerSupportsCancellation = true;
  30.             TaskbarProgress.SetState(thisProcess, TaskbarProgress.TaskbarStates.Paused);
  31.         }
  32.  
  33.         private void numericUpDown1_ValueChanged(object sender, EventArgs e)
  34.         {
  35.             primesNo = (int)numericUpDown1.Value;
  36.         }
  37.         private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
  38.         {
  39.             if (e.KeyCode == Keys.Enter)
  40.             {
  41.                 decimal value = Convert.ToDecimal(numericUpDown1.Text);
  42.                 try { numericUpDown1.Value = value; }
  43.                 catch (ArgumentOutOfRangeException)
  44.                 {
  45.                     if (value > numericUpDown1.Maximum) numericUpDown1.Value = numericUpDown1.Maximum;
  46.                     else if (value < numericUpDown1.Minimum) numericUpDown1.Value = numericUpDown1.Minimum;
  47.                 }
  48.                 button1_Click(sender, e);
  49.             }
  50.         }
  51.         private void button1_Click(object sender, EventArgs e)
  52.         {
  53.             doneCalculating = false;
  54.             calculate.RunWorkerAsync();
  55.             progressBar1.Value = progressBar2.Value = progressBar3.Value = progressBar4.Value = progressBar5.Value = progressBar6.Value = 0;
  56.             stage1progressMax = stage2progressMax = stage3progressMax = stage4progressMax = primesNo;
  57.             while (!doneCalculating)
  58.             {
  59.                 UpdateControls();
  60.                 UpdateControlValues();
  61.             }
  62.             UpdateControls();
  63.             UpdateControlValues();
  64.             totalProgress = stage1progress = stage2progress = stage3progress = stage4progress = stage5progress = 0;
  65.         }
  66.        
  67.         public void Calculate(object sender, DoWorkEventArgs e)
  68.         {
  69.             int[] primes = FindPrimes(primesNo);
  70.             string[] periods = new string[primesNo];
  71.             string[] relations = new string[primesNo];
  72.             string[] fileData = new string[primesNo];
  73.             DividePrimes(periods, ref primes);
  74.             FindRelation(periods, relations, ref primes);
  75.             FindPrimeRelations(ref primes, ref periods, ref fileData, ref relations);
  76.             FindDenominators(ref primes, ref relations);
  77.             doneCalculating = true;
  78.         }
  79.  
  80.         void UpdateControls()
  81.         {
  82.             progressBar1.Update();
  83.             progressBar2.Update();
  84.             progressBar3.Update();
  85.             progressBar4.Update();
  86.             progressBar5.Update();
  87.             progressBar6.Update();
  88.             label4.Update();
  89.             label5.Update();
  90.             label6.Update();
  91.             label7.Update();
  92.             label8.Update();
  93.             label10.Update();
  94.             groupBox1.Update();
  95.         }
  96.         void UpdateControlValues()
  97.         {
  98.             progressBar1.Value = totalProgress;
  99.             progressBar2.Value = (int)Math.Round(((double)stage1progress / (double)stage1progressMax) * 1000);
  100.             progressBar3.Value = (int)Math.Round(((double)stage2progress / (double)stage2progressMax) * 1000);
  101.             progressBar4.Value = (int)Math.Round(((double)stage3progress / (double)stage3progressMax) * 1000);
  102.             progressBar5.Value = (int)Math.Round(((double)stage4progress / (double)stage4progressMax) * 1000);
  103.             progressBar6.Value = (int)Math.Round(((double)stage5progress / (double)stage5progressMax) * 1000);
  104.             label4.Text = GetPercentageString(progressBar2.Value);
  105.             label5.Text = GetPercentageString(progressBar3.Value);
  106.             label6.Text = GetPercentageString(progressBar6.Value);
  107.             label7.Text = GetPercentageString(totalProgress);
  108.             label8.Text = GetPercentageString(progressBar4.Value);
  109.             label10.Text = GetPercentageString(progressBar5.Value);
  110.             TaskbarProgress.SetValue(thisProcess, totalProgress, 1000);
  111.         }
  112.         string GetPercentageString(int percent)
  113.         {
  114.             double percentage = (double)percent / 10;
  115.             string percentageString = percentage.ToString() + "%";
  116.             if (percent / 10 == percentage)
  117.                 percentageString = percentage.ToString() + ".0%";
  118.             return percentageString;
  119.         }
  120.         void FindPrimeRelations(ref int[] primes, ref string[] periods, ref string[] fileData, ref string[] relations)
  121.         {
  122.             char[] lastPrimeLength = primes[primesNo - 1].ToString().ToCharArray();
  123.             char[] biggestPeriodLength = periods.ToInt32Array().Max().ToString().ToCharArray();
  124.             for (int i = 0; i < primesNo; i++)
  125.             {
  126.                 string iString = primes[i].ToString();
  127.                 char[] iLength = iString.ToCharArray();
  128.                 char[] periodLength = periods[i].ToString().ToCharArray();
  129.                 fileData[i] += "1 / ";
  130.                 for (int j = 1; j < lastPrimeLength.Length - iLength.Length + 1; j++)
  131.                     fileData[i] += " ";
  132.                 fileData[i] += primes[i].ToString() + " | Period grade: ";
  133.                 for (int j = 1; j < biggestPeriodLength.Length - periodLength.Length + 1; j++)
  134.                     fileData[i] += " ";
  135.                 fileData[i] += periods[i];
  136.                 if (Convert.ToInt32(relations[i]) == 0)
  137.                     fileData[i] += "\t | No relation.";
  138.                 else if (Convert.ToInt32(relations[i]) == 1)
  139.                     fileData[i] += "\t |  k - 1";
  140.                 else
  141.                     fileData[i] += "\t | (k - 1) / " + relations[i];
  142.                 Progress(ref stage4progress, primesNo);
  143.             }
  144.             File.WriteAllLines("Primes - " + primesNo.ToString() + ".txt", fileData);
  145.         }
  146.         void FindDenominators(ref int[] primes, ref string[] relations)
  147.         {
  148.             int[] denominator = new int[primes[primesNo - 1]];
  149.             string[] denominators = new string[primes[primesNo - 1]];
  150.             stage5progressMax = denominators.Length;
  151.             for (int i = 0; i < denominator.Length; i++)
  152.                 denominators[i] = "None";
  153.             for (int i = 0; i < primes.Length; i++)
  154.             {
  155.                 denominator[Convert.ToInt32(relations[i])]++;
  156.                 denominators[Convert.ToInt32(relations[i])] = denominator[Convert.ToInt32(relations[i])].ToString();
  157.             }
  158.             char[] mostFrequentDenominatorLength = denominators[1].ToString().ToCharArray();
  159.             string[] denominatorFileData = new string[denominators.Length];
  160.             for (int i = 0; i < denominators.Length; i++)
  161.             {
  162.                 char[] iLength = denominators[i].ToCharArray();
  163.                 char[] currentDenominatorLength = i.ToString().ToCharArray();
  164.                 char[] lastDenominatorLength = denominators.Length.ToString().ToCharArray();
  165.                 for (int j = 1; j < lastDenominatorLength.Length - currentDenominatorLength.Length + 1; j++)
  166.                     denominatorFileData[i] += " ";
  167.                 denominatorFileData[i] += i.ToString() + ":\t";
  168.                 for (int j = 1; j < Math.Max(mostFrequentDenominatorLength.Length, 4) - iLength.Length + 1; j++)
  169.                     denominatorFileData[i] += " ";
  170.                 denominatorFileData[i] += denominators[i] + " (" + (((double)denominator[i] / (double)primesNo) * 100).ToString() + "%)";
  171.                 Progress(ref stage5progress, denominators.Length);
  172.             }
  173.             File.WriteAllLines("Denominators - " + primesNo.ToString() + ".txt", denominatorFileData);
  174.         }
  175.         int[] FindPrimes(int totalPrimes)
  176.         {
  177.             // Make further optimizations
  178.             int primesFound = 1;
  179.             Progress(ref stage1progress, primesNo);
  180.             int no = 3;
  181.             int[] primes = new int[totalPrimes];
  182.             primes[0] = 2;
  183.             while (primesFound < totalPrimes)
  184.             {
  185.                 bool isPrime = false;
  186.                 int totalNumbers = 0;
  187.                 for (int i = 1; i <= primes[primesFound - 1]; i++)
  188.                 {
  189.                     int intResult = no / i;
  190.                     double doubleResult = (double)no / (double)i;
  191.                     if ((double)intResult == doubleResult)
  192.                         totalNumbers++;
  193.                     if (totalNumbers > 1)
  194.                         break;
  195.                 }
  196.                 if (totalNumbers == 1)
  197.                     isPrime = true;
  198.                 if (isPrime)
  199.                 {
  200.                     primes[primesFound] = no;
  201.                     primesFound++;
  202.                     Progress(ref stage1progress, primesNo);
  203.                 }
  204.                 totalNumbers = 0;
  205.                 isPrime = false;
  206.                 no += 2;
  207.             }
  208.             return primes;
  209.         }
  210.         void DividePrimes(string[] periods, ref int[] primes)
  211.         {
  212.             for (int i = 0; i < primesNo; i++)
  213.             {
  214.                 bool period = false;
  215.                 int remainder = 10;
  216.                 int periodLength = 0;
  217.                 while (period == false)
  218.                 {
  219.                     while (remainder >= primes[i])
  220.                         remainder -= primes[i];
  221.                     remainder *= 10;
  222.                     periodLength++;
  223.                     if (remainder == 10)
  224.                         period = true;
  225.                     if (remainder == 0)
  226.                         break;
  227.                 }
  228.                 if (remainder == 10)
  229.                     periods[i] = periodLength.ToString();
  230.                 else if (remainder == 0)
  231.                     periods[i] = "0";
  232.                 Progress(ref stage2progress, primesNo);
  233.             }
  234.         }
  235.         void FindRelation(string[] periods, string[] relations, ref int[] primes)
  236.         {
  237.             for (int i = 0; i < primesNo; i++)
  238.             {
  239.                 for (int j = 1; j <= primes[i]; j++)
  240.                     if ((Convert.ToInt32(periods[i]) * j) + 1 == primes[i])
  241.                     {
  242.                         relations[i] = j.ToString();
  243.                         break;
  244.                     }
  245.                 Progress(ref stage3progress, primesNo);
  246.             }
  247.         }
  248.         private void Progress(ref int stage, int stageValue)
  249.         {
  250.             stage++;
  251.             int rawStagePercentage = (int)Math.Round(((double)stage / (double)stageValue) * 1000);
  252.             totalProgress = (int)Math.Round(((stage1progress / (decimal)stage1progressMax) + (stage2progress / (decimal)stage2progressMax) + (stage3progress / (decimal)stage3progressMax) + (stage4progress / (decimal)stage4progressMax) + (stage5progress / (decimal)stage5progressMax)) * 1000 / 5);
  253.         }
  254.     }
  255.     public static class Extensions
  256.     {
  257.         public static int Max(this int[] ar)
  258.         {
  259.             int max = int.MinValue;
  260.             for (int i = 0; i < ar.Length; i++)
  261.                 if (ar[i] > max)
  262.                     max = ar[i];
  263.             return max;
  264.         }
  265.         public static int[] ToInt32Array(this string[] ar)
  266.         {
  267.             int[] result = new int[ar.Length];
  268.             for (int i = 0; i < ar.Length; i++)
  269.                 result[i] = Convert.ToInt32(ar[i]);
  270.             return result;
  271.         }
  272.     }
  273.     public static class TaskbarProgress
  274.     {
  275.         public enum TaskbarStates
  276.         {
  277.             NoProgress = 0,
  278.             Indeterminate = 0x1,
  279.             Normal = 0x2,
  280.             Error = 0x4,
  281.             Paused = 0x8
  282.         }
  283.  
  284.         [ComImportAttribute()]
  285.         [GuidAttribute("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")]
  286.         [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  287.         private interface ITaskbarList3
  288.         {
  289.             // ITaskbarList
  290.             [PreserveSig]
  291.             void HrInit();
  292.             [PreserveSig]
  293.             void AddTab(IntPtr hwnd);
  294.             [PreserveSig]
  295.             void DeleteTab(IntPtr hwnd);
  296.             [PreserveSig]
  297.             void ActivateTab(IntPtr hwnd);
  298.             [PreserveSig]
  299.             void SetActiveAlt(IntPtr hwnd);
  300.  
  301.             // ITaskbarList2
  302.             [PreserveSig]
  303.             void MarkFullscreenWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen);
  304.  
  305.             // ITaskbarList3
  306.             [PreserveSig]
  307.             void SetProgressValue(IntPtr hwnd, UInt64 ullCompleted, UInt64 ullTotal);
  308.             [PreserveSig]
  309.             void SetProgressState(IntPtr hwnd, TaskbarStates state);
  310.         }
  311.  
  312.         [GuidAttribute("56FDF344-FD6D-11d0-958A-006097C9A090")]
  313.         [ClassInterfaceAttribute(ClassInterfaceType.None)]
  314.         [ComImportAttribute()]
  315.         private class TaskbarInstance { }
  316.  
  317.         private static ITaskbarList3 taskbarInstance = (ITaskbarList3)new TaskbarInstance();
  318.         private static bool taskbarSupported = Environment.OSVersion.Version >= new Version(6, 1);
  319.  
  320.         /// <summary>Used to change the TaskBarIcon's state.</summary>
  321.         public static void SetState(IntPtr windowHandle, TaskbarStates taskbarState)
  322.         {
  323.             if (taskbarSupported) taskbarInstance.SetProgressState(windowHandle, taskbarState);
  324.         }
  325.  
  326.         /// <summary>Used to change the TaskBarIcon's progress.</summary>
  327.         public static void SetValue(IntPtr windowHandle, double progressValue, double progressMax)
  328.         {
  329.             if (taskbarSupported) taskbarInstance.SetProgressValue(windowHandle, (ulong)progressValue, (ulong)progressMax);
  330.         }
  331.     }
  332.     public static class ISynchronizeInvokeExtensions
  333.     {
  334.         public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
  335.         {
  336.             if (@this.InvokeRequired)
  337.                 @this.Invoke(action, new object[] { @this });
  338.             else
  339.                 action(@this);
  340.         }
  341.     }
  342. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement