How to resolve the algorithm Sequence: smallest number greater than previous term with exactly n divisors step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sequence: smallest number greater than previous term with exactly n divisors step by step in the Swift programming language

Table of Contents

Problem Statement

Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors.

Show here, on this page, at least the first 15 terms of the sequence.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sequence: smallest number greater than previous term with exactly n divisors step by step in the Swift programming language

Source code in the swift programming language

// See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
    var n = number
    var total = 1
    // Deal with powers of 2 first
    while n % 2 == 0 {
        total += 1
        n /= 2
    }
    // Odd prime factors up to the square root
    var p = 3
    while p * p <= n {
        var count = 1
        while n % p == 0 {
            count += 1
            n /= p
        }
        total *= count
        p += 2
    }
    // If n > 1 then it's prime
    if n > 1 {
        total *= 2
    }
    return total
}

let limit = 32
var n = 1
var next = 1
while next <= limit {
    if next == divisorCount(number: n) {
        print(n, terminator: " ")
        next += 1
        if next > 4 && divisorCount(number: next) == 2 {
            n = 1 << (next - 1) - 1;
        }
    }
    n += 1
}
print()


  

You may also check:How to resolve the algorithm Sort disjoint sublist step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Compare a list of strings step by step in the C# programming language
You may also check:How to resolve the algorithm Tree traversal step by step in the Raku programming language
You may also check:How to resolve the algorithm 15 puzzle game step by step in the Rebol programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the Purity programming language