patterncsharpMinor
Read numbers until a prime is entered then print non-primes
Viewed 0 times
untilreadnonprimesnumbersprintthenenteredprime
Problem
I'm a beginner at C#. I just want to know what is the C# way to do this by its convention and a better algorithm as well.
using System;
using System.Collections.Generic;
public class Program
{
static public void Main()
{
bool prime = false;
List non_primes = new List();
while (prime == false)
{
int number = 0;
Console.Write("#: ");
number = Convert.ToInt32(Console.ReadLine());
prime = true;
for (int i = 2; i <= number / 2; i++)
{
if (number % i == 0)
prime = false;
if (prime == false)
non_primes.Add(number);
}
}
if (non_primes.Count != 0)
Console.WriteLine("none-primes: {0}", string.Join(" ", non_primes.ToArray()));
else
Console.WriteLine("none-primes: zero");
Console.WriteLine("press any key to continue");
Console.ReadKey();
}
}Solution
I am no C# programmer, so I can't tell you much about the "C# way" to code. But I'll try to help you with your algorithm.
First things first, if I'm not mistaken your for-loop may fill the list of non-primes multiple times for a given number if it has more than one divisor. I'd suggest using the
This will also save time by skipping unnecessary iterations. You should also increment by two instead of one, because all even numbers - and their multiples - will be divisible by two.
Since all numbers are either primes or multiples of primes you could further reduce compute time by skipping over numbers that are not prime. For example, fill an array with prime numbers below 100, then first try to divide the input by numbers in the array.
If it can't be divided by any of them, go back to the for-loop you already wrote and start from the highest prime you used.
First things first, if I'm not mistaken your for-loop may fill the list of non-primes multiple times for a given number if it has more than one divisor. I'd suggest using the
break; statement to exit the loop after you found the first, i.e.for (int i = 2; i <= number / 2; i++)
{
if (number % i == 0){
prime = false;
}
if (prime == false){
nones.Add(number);
break;
}
}This will also save time by skipping unnecessary iterations. You should also increment by two instead of one, because all even numbers - and their multiples - will be divisible by two.
Since all numbers are either primes or multiples of primes you could further reduce compute time by skipping over numbers that are not prime. For example, fill an array with prime numbers below 100, then first try to divide the input by numbers in the array.
If it can't be divided by any of them, go back to the for-loop you already wrote and start from the highest prime you used.
Code Snippets
for (int i = 2; i <= number / 2; i++)
{
if (number % i == 0){
prime = false;
}
if (prime == false){
nones.Add(number);
break;
}
}Context
StackExchange Code Review Q#125455, answer score: 4
Revisions (0)
No revisions yet.