To download NI software, including the products shown below, visit ni.com/downloads.
Overview
This VI is a basic programming exercise to find the amount of prime numbers within a given range.
Description
This VI consists of two for loops. The outer loop checks through each number within the range. The inner loop checks if that number is prime by evaluating the modulus. If the number is prime, the prime flag is set to true and the count increases.
Requirements
Software:
Steps to Implement or Execute Code
Additional Information or References
NI Snippet
**This document has been updated to meet the current required format for the NI Code Exchange.**
Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.
While this works, the Count of Primes wiring doesn't need to go through the inner loop. That can be wired around the loop (and shrink the box or that loop).
I found this post when researching how to compute the primes from 1 to N. It was a simple exercise from this example to modify it to give the list of primes. Here's what I did:
1. Add a null constant array input to a new shift register for the outer loop.
2. Wired the incoming shift register to the outer case structure.
3. Wired the current number under test in the inner loop to that same case structure.
4. Inside that structure for True, wired the current test number and the incoming shift register to a build array. Output of build array wired to pass out of the structure.
5. Inside that structure for False, just wire the incoming shift register to pass out of the case structure.
6. The new output from the case structure gets wired to the outgoing shift register.
7. The output of the shift register gets wired to a new array indicator.
The VI now provides both the list and count of primes in the range. However, it's now redundant, as the count is just the size of the new output array. So get rid of all the wiring for the Count of Primes, and instead use Array Size on the new outgoing shift register.
Oh, and I just realized that your example does not include 2 as a prime.
Experimenting a bit, I found that by setting the initial array constant to {2}, this now works.