Prime Numbers
A prime number is a whole number greater than 1, whose only two whole-number factors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.
A Prime Number can be divided evenly only by 1, or itself and it must be a whole number greater than 1.
Example: 5 can only be divided evenly by 1 or 5, so it is a prime number.
But 6 can be divided evenly by 1, 2, 3 and 6 so it is NOT a prime number (it is a composite number).
Take any number, say N and iterate the loop through N/2 from 2. If any one of the number is divisble with 0 remainder, then it is not a prime number and then exit from the loop.
The variable bPrime is used to store and return whether the given number is a prime number or not.
- Create a Windows Form Application.
File -> Project -> Windows Form Application.
Project Name : PrimeNumberWinForms.
- Switch to Property Window by pressing F4 function key. Set following properties Form1.
Form1.Text = Prime Numbers 0 To 1000
- Drag N Drop following controls on forms:
Control Type | Control (Name) ID | Description |
Button | btnPrimeNumbers | To generate prime numbers. Prime number generations logic written under this button click. |
Button | btnExit | To exit from this application. |
ListBox | lstPrimeNumbers | Result of button clicked and prime number will display with control. |
Change following properties of controls.
- btnPrimeNumbers.Text : Prime Numbers
- btnExit.Text : Exit
- lblResult.Text : [Result]
- lstPrimeNumbers.AutoSize : False
- lblResult.Width : 117
- lblResult.Height: 576
Double click on Exit button and write following code.
- btnExit click event code:
- private void btnExit_Click(object sender, EventArgs e)
- {
-
- this.Dispose();
- }
Double click on Prime Numbers button and write following code.
- btnPrimeNumbers click event code:
- private void btnPrimeNumbers_Click(object sender, EventArgs e)
- {
- lstPrimeNumbers.Items.Add("Prime Numbers From 0 To 1000.");
- for (int i = 0; i < 1000; i++)
- {
- if (CheckNumberPrimeNumber(i) == true) lstPrimeNumbers.Items.Add(i.ToString());
- }
- }
- CheckNumberPrimeNumber: This method will check number is prime number or not.
- public static bool CheckNumberPrimeNumber(int num)
- {
- bool CheckPrimeNumber = true;
- int factor = num / 2;
- int i = 0;
- for (i = 2; i <= factor; i++)
- {
- if ((num % i) == 0) CheckPrimeNumber = false;
- }
- return CheckPrimeNumber;
- }
You scroll to check prime number from 0 to 1000 in list box.
Please, feel free to asked any question related to this blog.