blog.gopenai.com Open in urlscan Pro
162.159.153.4  Public Scan

Submitted URL: http://blog.gopenai.com/optimizing-a-swift-function-for-calculating-the-digital-root-974aa6c7a763
Effective URL: https://blog.gopenai.com/optimizing-a-swift-function-for-calculating-the-digital-root-974aa6c7a763?gi=6637188af10c
Submission: On February 19 via api from US — Scanned from US

Form analysis 0 forms found in the DOM

Text Content

Open in app

Sign up

Sign in

Write


Sign up

Sign in




OPTIMIZING A SWIFT FUNCTION FOR CALCULATING THE DIGITAL ROOT

Mostafa Davoodi

·

Follow

Published in

GoPenAI

·
2 min read
·
Apr 26, 2023

25



Listen

Share

As a software engineer, I often encounter various coding problems, and I’m
always looking for ways to optimize my code for efficiency and performance.
Recently, I came across an interesting problem that required calculating the
Digital Root of a given integer. In this post, I’ll share my journey of
optimizing the solution in Swift.


THE PROBLEM

The task is to write a function that takes a non-negative integer as input and
returns its Digital Root. The Digital Root is the iterative process of summing
the digits of a number until a single-digit number is obtained.


INITIAL IMPLEMENTATION

Here’s the initial implementation in Swift:

func addDigits(_ num: Int) -> Int {
    var num = num
    while num > 9 { 
        num = Array(String(num)).map{ Int(String($0)) ?? 0 }.reduce(0,+)
    }
    return num
}

This implementation works, but it’s not very efficient as it creates new arrays
and strings in each iteration. This increases memory usage and runtime
complexity.


OPTIMIZED IMPLEMENTATION

To optimize the function, we can eliminate the use of arrays and strings by
using basic arithmetic operations:

func addDigits(_ num: Int) -> Int {
    var num = num
    while num > 9 {
        var sum = 0
        while num > 0 {
            sum += num % 10
            num /= 10
        }
        num = sum
    }
    return num
}

This version is more efficient as it avoids creating new arrays and strings in
each iteration.


FURTHER OPTIMIZATION USING DIGITAL ROOT FORMULA

After some research, I discovered that there’s an even more efficient solution
using the mathematical properties of numbers. The Digital Root can be calculated
using the following formula:

Digital Root = 1 + (num — 1) % 9

Using this formula, we can eliminate the need for loops and significantly
improve runtime:

func addDigits(_ num: Int) -> Int {
    if num == 0 {
        return 0
    } else {
        return 1 + (num - 1) % 9
    }
}

This version is highly efficient as it removes the need for any loops and
directly calculates the result using the given formula.


CONCLUSION

Optimizing code is an essential skill for every software engineer. By analyzing
the problem, understanding the underlying mathematical properties, and using
efficient algorithms, we can significantly improve the performance of our code.
In this case, we optimized the Digital Root calculation in Swift using the
Digital Root formula. This not only reduced memory usage but also resulted in a
much faster solution.

PS: This post description is generated by ChatGPT. I passed my 3 Swift
implementations for the Digital Root problem and asked it to generate a Medium
post based on them. The AI provided a comprehensive explanation of each
implementation, showing the optimization process and improvements made along the
way.





SIGN UP TO DISCOVER HUMAN STORIES THAT DEEPEN YOUR UNDERSTANDING OF THE WORLD.


FREE



Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.


Sign up for free


MEMBERSHIP



Access the best member-only stories.

Support independent authors.

Listen to audio narrations.

Read offline.

Join the Partner Program and earn for your writing.


Try for $5/month
Algorithms
Software Engineering
Problem Solving
ChatGPT


25

25



Follow



WRITTEN BY MOSTAFA DAVOODI

12 Followers
·Writer for

GoPenAI

Senior Software Engineer, https://www.linkedin.com/in/mostafa-davoodi/

Follow




MORE FROM MOSTAFA DAVOODI AND GOPENAI

Mostafa Davoodi

in

GoPenAI


SOLVING COIN CHANGE PROBLEM WITH DYNAMIC PROGRAMMING IN SWIFT


HELLO PROBLEM SOLVERS! TODAY, I AM EXCITED TO WALK YOU THROUGH A CLASSIC
COMPUTER SCIENCE PROBLEM: THE COIN CHANGE PROBLEM.

3 min read·May 23, 2023



Júlio Almeida

in

GoPenAI


OPEN-SOURCE LLM DOCUMENT EXTRACTION USING MISTRAL 7B


INTRODUCTION

6 min read·Feb 2, 2024

277

2




Sanjay Singh

in

GoPenAI


A STEP-BY-STEP GUIDE TO TRAINING YOUR OWN LARGE LANGUAGE MODELS (LLMS).


LARGE LANGUAGE MODELS (LLMS) HAVE TRULY REVOLUTIONIZED THE REALM OF ARTIFICIAL
INTELLIGENCE (AI). THESE POWERFUL AI SYSTEMS, SUCH AS GPT-3…

10 min read·Sep 30, 2023

205





Mostafa Davoodi

in

GoPenAI


DETERMINING ISOMORPHIC STRINGS: A SWIFT SOLUTION


HELLO SWIFT DEVELOPERS! TODAY WE ARE GOING TO DIVE INTO AN INTERESTING STRING
MANIPULATION PROBLEM: DETERMINING IF TWO STRINGS ARE…

2 min read·May 22, 2023


See all from Mostafa Davoodi
See all from GoPenAI



RECOMMENDED FROM MEDIUM

Munendra Pratap Singh


IOS MOBILE APP SECURITY: BEST PRACTICES FOR IOS MOBILE DEVELOPERS.


IOS DEVELOPERS MUST PRIORITIZE CODE SECURITY, DATA STORAGE, AND COMMUNICATION
SECURITY BASED ON OWASP TOP 10. ALTHOUGH IOS IS LESS…

6 min read·Feb 10, 2024

139

1




Jacob Bennett

in

Level Up Coding


THE 5 PAID SUBSCRIPTIONS I ACTUALLY USE IN 2024 AS A SOFTWARE ENGINEER


TOOLS I USE THAT ARE CHEAPER THAN NETFLIX


·5 min read·Jan 4, 2024

9.2K

100





LISTS


CHATGPT

21 stories·469 saves


WHAT IS CHATGPT?

9 stories·295 saves


THE NEW CHATBOTS: CHATGPT, BARD, AND BEYOND

12 stories·307 saves


CHATGPT PROMPTS

42 stories·1134 saves


Artturi Jalli


I BUILT AN APP IN 6 HOURS THAT MAKES $1,500/MO


COPY MY STRATEGY!


·3 min read·Jan 23, 2024

9K

119




Byungwook An


LIBRARY VS FRAMEWORK VS PACKAGE IN SWIFT


INTRO

3 min read·Feb 8, 2024

11





Andrew Zuo


GOOGLE’S GEMINI IS BETTER THAN GPT


I RECENTLY PUT GPT 4 INTO MY APP AND IT WAS PRETTY GOOD AT FIRST. BUT THEN IT
WAS NOT SO GOOD. GPT 4, FOR WHATEVER REASON, DECIDED TO TAKE…


·4 min read·Feb 10, 2024

712

7




Sendbird

in

Dev Genius


SWIFTUI VS. UIKIT: WHAT IS THE BEST CHOICE FOR BUILDING AN IOS USER INTERFACE IN
2024?


HELP YOUR IOS APP DEVELOPMENT TEAM FINALLY DECIDE BETWEEN SWIFTUI VS. UIKIT.

10 min read·Feb 9, 2024

87

4



See more recommendations

Help

Status

About

Careers

Blog

Privacy

Terms

Text to speech

Teams