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,181 questions

56,073 answers

573 users

How to compute the factorial of a number greater than 20 in Swift

1 Answer

0 votes
//
//  This program computes the factorial of numbers greater than 20.
//  Swift's built‑in Int cannot store extremely large values,
//  so we implement a simple arbitrary‑precision integer using base‑10 digits.
//

import Foundation

//
//  A minimal BigInt type using base‑10 digits.
//  Digits are stored least‑significant first for easy multiplication.
//
struct BigInt {
    var digits: [Int] = [1]   // represents the number 1

    // Multiply BigInt by a small Int
    mutating func multiply(by n: Int) {
        var carry = 0

        for i in 0..<digits.count {
            let product = digits[i] * n + carry
            digits[i] = product % 10
            carry = product / 10
        }

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

    // Convert BigInt to a human‑readable string
    func toString() -> String {
        digits.reversed().map(String.init).joined()
    }
}

//
//  Compute factorial using BigInt.
//  The algorithm multiplies numbers from 2 to n.
//
func factorialBig(_ n: Int) -> BigInt {
    var result = BigInt()

    for i in 2...n {
        result.multiply(by: i)
    }

    return result
}

//
//  Main program: read input, compute factorial, print result.
//
print("Enter a number greater than 20: ", terminator: "")
let input = readLine() ?? "0"
let n = Int(input) ?? 0

let result = factorialBig(n)

print("\nFactorial of \(n) is:\n")
print(result.toString())


/*
run:

Enter a number greater than 20: 25

Factorial of 25 is:

15511210043330985984000000

*/

 



answered 3 days ago by avibootz

Related questions

...