Prime Number Checker in Excel VBABelow we will look at a program in Excel VBA that checks whether a number is a prime number or not. Before you start: in mathematics, a prime number is a number that has exactly two distinct number divisors: 1 and itself.
The smallest twenty- five prime numbers are: 2, 3, 5, 7, 1. For example, 8 has 1, 2, 4 and 8 as divisors and is not a prime number. Situation: 1. First, we declare three variables. One Integer variable we call divisors, one Long variable we call number and one Long variable we call i. We use Long variables here because Long variables have larger capacity than Integer variables. Dim divisors As. Integer, number As. Long, i As. Long. We initialize two variables. We initialize the variable divisors with value 0. We use the Input. A prime number (or a prime). There are various methods to determine whether a given number n is prime. The most basic routine. C PROGRAM: Prime Factorization. Box function to get a number from the user. Input. Box(. Remember, a prime number has exactly two distinct number divisors: 1 and itself. We start a For Next loop. For i = 1 To number. Now comes the most important part of the program. To calculate the number of divisors of a number, we use the Mod operator. The Mod operator gives the remainder of a division. So 7 mod 2 would give 1. In this case we want to increment the variable divisors by 1. The macro below does the trick. If number Mod i = 0 Thendivisors = divisors + 1. End. If. Excel VBA checks this for i = 1, i = 2, i = 3, i = 4 until i = number. Note that i = 1 and i = number always are divisors of number. Only if these numbers are the only divisors of number, the number is a prime number. Don't forget to close the loop. Next i. 6. If divisors equals 2, we display a msgbox saying that the entered number is a prime number. If the number of divisors is higher than 2, we display a msgbox saying that the entered number is not a prime number. If divisors = 2 Then. Msg. Box number & . Test the program. Result for 1. 04.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
August 2017
Categories |