Swift program to display prime numbers between two intervals


This tutorial will discuss how to write swift program to display prime numbers between two intervals.

Prime numbers are those numbers that are greater than 1 and has exactly two factors that is 1 and the number itself. For example, 3 is the prime number because it has only two factors that are 1 and 3.

Below is a demonstration of the same −

Input

Suppose our given input is −

Lower Interval = 18
Upper Interval = 42

Output

The desired output would be −

Prime numbers between 18 to 42 are
19
23
29
31
37
41

Algorithm

Following is the algorithm −

Step 1 − Declare lower and upper interval.

Step 2 − Iterate through each number in the given interval.

Step 3 − Skip 1 and 0 because they are not prime numbers

Step 4 − Declare a flag variable. It represent if the given number is prime or not. If the flag = 0, then the number is prime number. Otherwise not.

Step 5 − Run another for loop to check the given number is prime number or not.

Step 6 − Print the output.

Example

The following program shows how to display prime numbers between two intervals.

import Foundation
import Glibc
// Declaring lower and upper interval
var lowerInterval = 18
var upperInterval = 36
print("Prime numbers in between (lowerInterval) to (upperInterval)")
// Iterate through each number in the given interval
// Here we use upperInterval+1 because stride () function work from 18 to 35 not 36. 
for x in stride(from:lowerInterval, to: upperInterval+1, by:1){
   // Here we skip 1 because 1 is not a prime number
   if (x == 0 || x == 1){
      continue
   }
   // Flag tells if x is a  prime number or not
   var flag = 0
    
   for y in stride(from:2, to: x/2 + 1, by:1){
      // Checking x is divisible by y, if remainder = 0 then the number is not prime number
      if ((x % y) == 0){
         flag = 1
         break
      }
   }
   // If the flag = 0 then the number is  prime number or else it is not a prime number
   if (flag == 0){
      print(x)
   }
}

Output

Prime numbers in between 18 to 36
19
23
29
31

Here, in the above code, we find prime number in between 18 to 36. Here, we use nested for loop along with stride() function. Outer for loop is used to iterate through each number present in between the given interval and inner for loop is used to check the given number is prime number or not by finding the remainder.

for y in stride(from:2, to: x/2 + 1, by:1){
   if ((x % y) == 0){
      flag = 1
      break
   }
}

If the remainder is equal to 0, then the number is not prime number, so flag = 1 and break the loop. If the remainder is not equal to 0, then the number is prime number, so the flag = 0 and display that number. This process will continue till upper Interval.

Updated on: 13-Dec-2022

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements