In: Computer Science
A positive integer n is said to be prime (or, "a prime") if and only if n is greater than 1 and is divisible only by 1 and n . For example, the integers 17 and 29 are prime, but 4, 21 and 38 are not prime. Write a function named "is_prime" that takes a positive integer argument and returns as its value the integer 1 if the argument is prime and returns the integer 0 otherwise.
Can you make it in vba excel and in the form of functions because its hard for me
SOLUTION
The following function has been created as part of the VBA module for an Excel Workbook.
PROGRAM
Function is_prime(number As Integer) As Integer
'Declare the variables
Dim divisor As Integer
Dim i As Long
Dim prime As Integer
'Initialize divisor to zero
divisor = 0
'Start a for loop
For i = 1 To number
'Check for perfect divisors
If number Mod i = 0 Then
'Increment the divisor by 1
divisor = divisor + 1
End If
'Close loop
Next i
'If divisor is 2 then the number is prime and so return 1
If divisor = 2 Then
is_prime = 1
Else
'Is not prime and hence return 0
is_prime = 0
End If
End Function
Note:
Notice that the return variable is the same as that of the function name(is_prime)
Kindly refer to the screenshot for indentation related queries.
SCREENSHOT
PROGRAM
The VBA developer window is shown along with the corresponding Excel Workbook.
SAMPLE OUTPUT 1
Here you can see a list of numbers from A2:A13 whose values have to be determined whether they are prime or not.
In the cell B2 call the function "is_prime" by entering the formula
=is_prime(A2)
Here you are passing on the value of Cell A2 as a parameter. Click Enter. The value of either '0' or '1' is returned based on the prime property of the parameter.
Drag the fill handle till cell B13 to calculate the same for the range.
Here the function is called for
a single cell output
=is_prime(27)
The result is returned to the same cell.
Hope this helps...