Find prime numbers and traverse lists in a circular manner.

Store the first n prime numbers in the array

The following program stores the first n prime numbers in an array. The value of n is chosen by the user, and any number can be used. Here’s how to solve this problem:

  • Start with an empty array of n elements.

  • Store 22 as the first prime number at the 0th0^{th} index.

  • Keep checking every following integer by dividing it by every prime value in the array.

    • Check 33 by taking the remainder after dividing it by all the prime values in the array. The only value in the current array is 22. Since the remainder is non-zero, 33 is stored in the array.

    • Then, check 44 in the same way. Since the remainder of 44 divided by 22 is 00, it’s not stored in the array.

In the above code:

  • The variable n shows the total number of prime numbers.

  • The first if statement specifies that the value of n shouldn’t be less than 1.

  • We create an array of n values (i.e., Array(n)). The syntax Array(n).fill(2) is used to create an array of n elements, each having a value of 2.

  • We use two nested while loops.

    • The outer loop counts the number of generated prime numbers.

    • The inner loop keeps generating sequential integers until the next prime number is found.

  • We use the following variables:

    • n stores the total number of prime numbers.

    • p stores the generated prime numbers.

    • pcount keeps track of the most recently generated prime number.

    • v stores the next number to be tested.

    • i iterates through the array of prime numbers generated so far.

    • pflag indicates whether the current number is prime.

The comments in the program itself will help explain the rest of the code.

Circular traversal

The following program demonstrates circular moves in an array using the positive numbers in that array. The program makes the value of the cell that is shown negative and ends when all values are negative.

To solve this problem, we first need to understand circular traversals.

Get hands-on with 1400+ tech skills courses.