DataWeave Interview Question: Find If Prime Number
This article will help you practice your DataWeave skills in MuleSoft. We're going to find out if an input number is prime or not.
A prime number is a number that is greater than 1 and divided by 1 or itself. In other words, prime numbers can't be divided by other numbers than themselves or 1. For example 2, 3, 5, 7, 11, 13, 17, 19, 23.... are the prime numbers.
Note: Please use 3 or greater than 3 for this logic.
Input Payload:
xxxxxxxxxx
7
Output Result:
xxxxxxxxxx
"7 is prime number"
In Step 1, we will apply a map starting from 2 till (payload - 1).
After that, we will use the mod operator to check reminders of payload by item.
Step 1 Code:
xxxxxxxxxx
%dw 2.0
output application/json
---
(2 to payload-1) map ((item, index) -> payload mod item)
Step 1 Output:
xxxxxxxxxx
[
1,
1,
3,
2,
1
]
In Step 2, we will use an if statement and check whether the output array of our previous step contains 0 or not.
If 0 is present it means our payload is completely divided by another number and hence it is not a prime number.
If 0 is not present it means our payload is not completely divided by another number and hence it is a prime number.
Final Code:
xxxxxxxxxx
%dw 2.0
output application/json
---
if(((2 to payload-1) map ((item, index) -> payload mod item) contains 0) == true) payload ++ " is not prime number" else payload ++ " is prime number"
Output:
xxxxxxxxxx
"7 is prime number"
Hope this helps improve your DataWeave skills. I am not an expert on DataWeave. I am just sharing what I can solve. Comments are welcome. Thanks.
Opinions expressed by DZone contributors are their own.