/// <summary> /// TASK: найти максимальную неубывающую последовательность /// </summary> static public void RunMaximumDoesNotDecreaseSequence() { WorkWithTheConsole.OutputTitle("Найти максимальную неубывающую последовательность"); InputOneDimensionalArray(); MaximumDoesNotDecreaseSequence(array); WorkWithTheConsole.ScreenDelay(); }
// поиск суммы второго наибольшего и второго наименьшего элемента массива internal static string FindSummaTwoSmallestAndTwoLargestElementArray(int[] array) { int number = array[0]; bool flag = false; Array.Sort(array); for (int i = 1; i < array.Length; i++) { if (array[i] != number) { flag = true; } } if (flag) { WorkWithTheConsole.Output("The 2nd largest elements = ", array[1]); WorkWithTheConsole.Output("The 2nd smallest element = ", array[array.Length - 2]); WorkWithTheConsole.Output("The sum of the 2nd largest and 2nd smallest elements of the array = {0}\n", array[1] + array[array.Length - 2]); return((array[1] + array[array.Length - 2]).ToString()); } else { WorkWithTheConsole.OutputError("All elements are equal\n"); return("All elements are equal"); } }
// ввод одномерного массива static void InputOneDimensionalArray() { InputInvalidSizeArray(ref arraySize, "Enter size massif: "); array = new int[arraySize]; for (int i = 0; i < array.Length; i++) { WorkWithTheConsole.InputInt32("Enter " + i + " element massif: ", ref array[i]); } }
//ввод натурального числа static void InputNaturalNumber() { WorkWithTheConsole.InputInt32("Enter natural number: ", ref numberN); if (numberN <= 0) { WorkWithTheConsole.OutputError("This is not a natural number \n"); WorkWithTheConsole.InputInt32("Enter natural number: ", ref numberN); } }
static void OutputFactorialNumbersAsTheProductOfThreeConsecutivePrimes(bool flag) { if (flag) { WorkWithTheConsole.Output(numberN + "! = " + Factorial(numberN) + ": " + multiplication3PrimeNumber + "\n"); } else { WorkWithTheConsole.OutputError("can not imagine " + numberN + "! = " + Factorial(numberN) + " as a product of three consecutive prime numbers \n"); } }
// вывод на экран решение задачи по поиску совершенных чисел на отрезке static void OutputPerfectNumbers(string perfectNumber, bool flag) { if (flag) { WorkWithTheConsole.Output("Perfect number:", perfectNumber); } else { WorkWithTheConsole.OutputError("No perfect numbers \n"); } }
// вывод на экран решение задачи на определение являются ли два числа взаимнопростыми static void OutputMutuallySimpleNumbers() { if (naturalNumberFlag == true) { WorkWithTheConsole.OutputError("Number 0 it is not natural, therefore it can not be coprime with any number\n"); } else if (NOD == 1) { WorkWithTheConsole.OutputVerity("Numbers " + firstNumber + " and " + secondNumber + " are mutually simple, because their NOD = 1 \n"); } else { WorkWithTheConsole.OutputError("Numbers " + firstNumber + " and " + secondNumber + " are not mutually simple, because their NOD != 1 \n"); } }
static int[] array; // одномерный массив // проверка на корректность ввода размера массива для чтения с консоли (тесты виснут из-за консоли) static void InputInvalidSizeArray(ref int size, string textConsole) { int number = 0; WorkWithTheConsole.InputInt32(textConsole, ref number); if (number <= 0) { WorkWithTheConsole.OutputError("ERROR. The size of the array must be a positive number\n"); InputInvalidSizeArray(ref size, textConsole); } else { size = number; } }
// поиск максимальной неубвающей последовательности internal static int[] MaximumDoesNotDecreaseSequence(int[] array) { int iStartMax = -1; // индекс 1-ого элемента макс последовательности int iFinMax = -1; // индекс последнего элемента макс последовательности int amountMax = -1; // максимальное количество элементов в макс последовательности int amountCurrent = 0; // максимальное количество элемонтов в тек последовательности int iStartCurrent = -1; // индекс 1-ого элемента текущей последовательности int iFinCurrent = -1; // индекс последнего элемента текущей последовательности bool flag = false; // флаг для проверки неубывающей последовательности for (int i = 0; i < array.Length - 1; i++) { if (array[i] <= array[i + 1]) { if (!flag) { flag = true; iStartCurrent = i; } iFinCurrent = i + 1; amountCurrent += 1; if (amountCurrent > amountMax) { iStartMax = iStartCurrent; iFinMax = i + 1; amountMax = amountCurrent; } } else { amountCurrent = 0; flag = false; } } if (amountMax != -1) { WorkWithTheConsole.Output("Start array: "); for (int i = 0; i < array.Length; i++) { WorkWithTheConsole.Output(" "); WorkWithTheConsole.Output(array[i]); } WorkWithTheConsole.Output("\nStart index maximum sequence: ", iStartMax); WorkWithTheConsole.Output("Finish index maximum sequence: ", iFinMax); WorkWithTheConsole.Output("Maximum sequence: "); for (int i = iStartMax; i <= iFinMax; i++) { WorkWithTheConsole.Output(" "); WorkWithTheConsole.Output(array[i]); } // для тестов int[] arrayTests = new int[iFinMax - iStartMax + 1]; int j = 0; for (int i = iStartMax; i <= iFinMax; i++) { arrayTests[j] = array[i]; ++j; } return(arrayTests); } else { WorkWithTheConsole.OutputError("Does not decrease sequence missing"); return(null); } }
/// <summary> /// TASK: найти совершенные числа на отрезке /// </summary> static public void RunPerfectNumbersOnALine() { WorkWithTheConsole.OutputTitle("Найти совершенные числа на отрезке"); InputStartAndEndSegment(); PerfectNumberToFind(startLine, finishLine); }
// ввод двух целых чисел static void InputWholeNumbers() { WorkWithTheConsole.InputInt32("Enter 2 whole numbers\n 1st number = ", ref firstNumber); WorkWithTheConsole.InputInt32(" 2st number = ", ref secondNumber); }
// вывод на экран решение задачи по переводу числа из десятиричной системы в двоичную static void OutputTranslationFromDecimalSystemToBinary(int numberDecimalSystem, string numberBinarySystem) { WorkWithTheConsole.Output("Number " + numberDecimalSystem + " in 2-digit number system = " + numberBinarySystem + "\n"); }
/// <summary> /// TASK: Определить можно ли представить N! в виде произведения трех последовательных простых чисел /// </summary> public static void RunFactorialNumbersAsTheProductOfThreeConsecutivePrimes() { WorkWithTheConsole.OutputTitle("Определить можно ли представить N! в виде произведения трех последовательных простых чисел"); InputNaturalNumber(); FactorialNumbersAsTheProductOfThreeConsecutivePrimes(numberN); }
// ввод числа в десятиричной системе static public void InputNumberInDecimalSystem() { WorkWithTheConsole.InputInt32("Enter a number in a 10-digit number system: ", ref numberDecimalSystem); }
/// <summary> /// TASK: найти сумму второго наибольшего и второго наименьшего элемента массива /// </summary> static public void RunSummaTwoSmallestAndTwoLargestElementArray() { WorkWithTheConsole.OutputTitle("Найти сумму второго наибольшего и второго наименьшего элемента массива"); InputOneDimensionalArray(); FindSummaTwoSmallestAndTwoLargestElementArray(array); }
/* // проверка на корректность ввода целых чисел * static public void InputValidationInt32(ref int number, string textConsole) * { * try * { * WorkWithTheConsole.Output(textConsole); * number = Convert.ToInt32(Console.ReadLine()); * } * catch (Exception) * { * WorkWithTheConsole.OutputError("DATA TYPE ERROR. Enter a number"); * InputValidationInt32(ref number, textConsole); * } * } */ // проверка на ввод натуральных чисел static public void InputValidationNaturalNumber(ref int number, string textConsole) { WorkWithTheConsole.Output(textConsole); number = Convert.ToInt32(Console.ReadLine()); }
/// <summary> /// TASK: определить являются ли целые числа взаимпнопростыми /// </summary> static public void RunMutuallySimpleNumber() { WorkWithTheConsole.OutputTitle("Определить являются ли целые числа взаимпнопростыми"); InputWholeNumbers(); GreatestCommonDivisorEvclidAlgorithm(firstNumber, secondNumber); }
// ввод начала и конца отрезка, в котором требуется найти совершенные числа static void InputStartAndEndSegment() { WorkWithTheConsole.InputInt32("Enter start and end of the line\n Enter start line: ", ref startLine); WorkWithTheConsole.InputInt32("Enter end line:", ref finishLine); }
// вывод на экран темы static internal string OutputTitle(string textTitle) { WorkWithTheConsole.Output("\n\t\tTASK: " + textTitle + "\n"); return("\n\t\tTASK: " + textTitle + "\n"); }
/// <summary> /// TASK: перевод из десятиричной системы исчисления в двоичную /// </summary> static public void RunTranslationOfNumberSystems() { WorkWithTheConsole.OutputTitle("Перевод из десятиричной системы исчисления в двоичную"); InputNumberInDecimalSystem(); TranslationFromDecimalSystemToBinary(numberDecimalSystem); }