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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to calculate power for large numbers in Swift

1 Answer

0 votes
import Foundation

func calculateLargeNumbersPower(base: Int, exponent: Int) -> [Int] {
    var digits = [1] // Least significant digit first

    for _ in 1...exponent {
        var carry = 0
        for i in 0..<digits.count {
            let num = digits[i] * base + carry
            digits[i] = num % 10
            carry = num / 10
        }

        while carry > 0 {
            digits.append(carry % 10)
            carry /= 10
        }
    }

    return digits
}

func digitsToStringReversed(_ digits: [Int]) -> String {
    return digits.reversed().map(String.init).joined()
}

let testCases = [15, 100]
for n in testCases {
    let digits = calculateLargeNumbersPower(base: 2, exponent: n)
    let resultString = digitsToStringReversed(digits)
    print("2^\(n) = \(resultString)")
}



/*
run:

2^15 = 32768
2^100 = 1267650600228229401496703205376

*/

 



answered Aug 2, 2025 by avibootz

Related questions

1 answer 124 views
1 answer 127 views
1 answer 145 views
1 answer 144 views
1 answer 145 views
...