Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to check if a number is circular prime (cyclically rotate left will also be prime) in Swift

1 Answer

0 votes
import Foundation

func isPrime(_ n: Int) -> Bool {
    if n == 2 { return true }
    if n < 2 || n % 2 == 0 { return false }

    let limit = Int(sqrt(Double(n)))
    for i in stride(from: 3, through: limit, by: 2) {
        if n % i == 0 { return false }
    }
    
    return true
}

func cyclicallyRotateLeft(_ n: Int) -> Int {
    var m = n
    var p = 1
    
    while m >= 10 {
        p *= 10
        m /= 10
    }
    
    return (n % p) * 10 + m
}

func isCircularPrime(_ n: Int) -> Bool {
    if n < 2 { return false }

    var rotated = cyclicallyRotateLeft(n)
    while rotated != n {
        if rotated < n || !isPrime(rotated) {
            return false
        }
        rotated = cyclicallyRotateLeft(rotated)
    }
    
    return true
}

let testNumbers = [197, 1193, 23, 101, 119]

for n in testNumbers {
    let result = isCircularPrime(n) ? "Circular Prime" : "Not Circular Prime"
    print("\(n) → \(result)")
}

// 1193
// 1193 = prime
// 3119 = prime
// 9311 = prime
// 1931 = prime

/*
run:

197 → Circular Prime
1193 → Circular Prime
23 → Not Circular Prime
101 → Not Circular Prime
119 → Circular Prime

*/

 



answered Nov 10, 2025 by avibootz
...