Saturday, August 31, 2013

Write the prime Number code which output like this?

@MVP


I did forget to write some english, sorry for that.


The reason why your code is inefficient is because its complexity is linear to the size of the sqrt of the number to be checked, while my adapted version is linear to the size of the primes list.


A prime number is a number that always has a rest fraction when divided by any natural number < itself and > 1.


So say we're looking to see if x is prime, suppose there exists a number n with the properties n < x, n > 1, x % n = 0. Our x is not a prime, but what about n? If n is a prime it's all good (it's in the primes List<int>) but if it's not a prime that would mean there exists natural numbers r, s for which r > 1, r < n, n % r = 0, n = rs. Substituting that in the equation above gets us x % rs = 0 which implies x % r = 0 and x % s = 0. So in this case it would've been sufficient to check the rest fraction of x divided by the smaller numbers r and s instead of n, which completes the proof ;)


Also, sometimes a piece of code says more than a thousand words, if i were to really clean up your code (untested):




using System;
using System.Linq;
using System.Collections.Generic;

namespace Csharp
{
public class MainTest
{
static List<int> primes = new List<int>();

static bool IsPrime(int num)
{
return (from x in primes where num % x == 0 select x).Count() == 0;
}

static void Main(string[] args)
{
Console.WriteLine("Please input a number:");
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Results are:");
int cnt = 1;
while (primes.Count < num)
{
cnt++;
if (!IsPrime(cnt))
continue;
primes.Add(cnt);
Console.WriteLine(cnt);
}
}
}
}



have a good day











No comments:

Post a Comment