Find prime numbers and traverse lists in a circular manner.
We'll cover the following
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 as the first prime number at the index.
-
Keep checking every following integer by dividing it by every prime value in the array.
-
Check by taking the remainder after dividing it by all the prime values in the array. The only value in the current array is . Since the remainder is non-zero, is stored in the array.
-
Then, check in the same way. Since the remainder of divided by is , 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 ofn
shouldn’t be less than1
. -
We create an array of
n
values (i.e.,Array(n)
). The syntaxArray(n).fill(2)
is used to create an array ofn
elements, each having a value of2
. -
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.