Example Code

Find Primes in Range Example

Products and Environment

This section reflects the products and operating system used to create the example.

To download NI software, including the products shown below, visit ni.com/downloads.

    Software

  • LabVIEW

Code and Documents

Attachment

Download All

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:

  1. LabVIEW 2012

 

Steps to Implement or Execute Code

  1. Open VI
  2. Input a range of numbers
  3. Run the VI and observe how many prime numbers are between number 1 and 2

 

Additional Information or References
NI Snippet

1.png 

 **This document has been updated to meet the current required format for the NI Code Exchange.**

Applications Engineer
National Instruments

Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.

Comments
StaceyG
Member
Member
on

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. 

 

 

StaceyG
Member
Member
on

Oh, and I just realized that your example does not include 2 as a prime.

StaceyG
Member
Member
on

Experimenting a bit, I found that by setting the initial array constant to {2}, this now works.