Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Write a method that calculates all prime numbers in given range and returns them as list of integers.Write a method to print a list of integers. Write a program that enters two integer numbers (each at a separate line) and prints all primes in their range, separated by a comma.
- namespace _03.PrimesInGivenRange
- {
- using System;
- using System.Collections.Generic;
- public class PrimesInGivenRange
- {
- public static void Main(string[] args)
- {
- checked
- {
- int startNum;
- do
- {
- Console.Write("Enter a non-negative Integer number: ");
- }
- while (!int.TryParse(Console.ReadLine(), out startNum) || startNum < 0);
- int endNum;
- do
- {
- Console.Write("Enter other non-negative Integer number, Bigger from the First: ");
- }
- while (!int.TryParse(Console.ReadLine(), out endNum) || endNum <= startNum);
- List<int> primes = FindPrimesInGivenRangeAndPutThemInTheList(startNum, endNum);
- PrintListOfIntegers(primes);
- }
- }
- private static void PrintListOfIntegers(List<int> numsList)
- {
- checked
- {
- if (numsList.Count > 0)
- {
- Console.WriteLine("The Prime Numbers In Given Range are:");
- for (int i = 0; i < numsList.Count; i++)
- {
- Console.Write(numsList[i]);
- if (i < numsList.Count - 1)
- {
- Console.Write(", ");
- }
- }
- Console.WriteLine();
- }
- else
- {
- Console.WriteLine("In Given Range No Any Prime Number!");
- Console.WriteLine("(empty list)");
- }
- }
- }
- private static List<int> FindPrimesInGivenRangeAndPutThemInTheList(int start, int end)
- {
- checked
- {
- List<int> primes = new List<int>();
- for (int num = start; num <= end; num++)
- {
- bool isPrimeNum = CheckTheIntegerNumberIsPrimeOrNot(num);
- if (isPrimeNum)
- {
- primes.Add(num);
- }
- }
- return primes;
- }
- }
- private static bool CheckTheIntegerNumberIsPrimeOrNot(int num)
- {
- checked
- {
- if (num < 2)
- {
- return false;
- }
- else
- {
- bool isPrime = true;
- int maxDivider = (int)Math.Sqrt(num);
- for (int i = 2; i <= maxDivider; i++)
- {
- if (num % i == 0)
- {
- isPrime = false;
- break;
- }
- }
- return isPrime;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement