Introduction
Recently I wrote the post Learn Big O Notation once and for all. In that post I go over all of the types of Big O time notation that is available at the Big-O cheatsheet. And I did not think there would be any more time notations possible outside of those seven.
As if the universe itself was humbling me and mocking my ignorance, I encountered a LeetCode problem with a solution of O(√n) time. Which could be translated to O(N^1/2), if you're crazy.
The problem
You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.
The obvious solution
Well, if you're like me your first thought was to go through every number from 1 to n, check if it is a factor, and if it is in the desired k index, return it.
The code looks like this:
def getkthFactorOfN(n, k): result = 0 for i in range(1, n + 1): if n % i == 0: result = result + 1 if result == k: return i return -1
This is all fine and dandy, but it is "only" O(n). After all, there is only one loop and it goes up to n 1.
Every other operation is discarded when considering the time notation.
But, my friend, there's a catch.
Understanding factors
If you think about it, factors are "mirrored" after a certain point.
Take, for example, the number 81. Its factors are [1, 3, 9, 27], where:
- 1 * 81 = 81
- 3 * 27 = 81
- 9 * 9 = 81
- 27 * 3 = 81
- 81 * 1 = 81
If you don't count the number 9, The operations are simply repeated and flipped. If you divide n by one of its factors, you get another factor.
Expect the square root of n, where it is itself squared (duh).
Armed with this knowledge, we now know that we don't need to iterate through the loop up to n times (with range(1, n 1)), but simply up to math.sqrt(n). After that, we've got every factor we need!
The not-so-obvious solution
Now that we have everything we need, we need to transform this loop from 1 -> n to 1 -> sqrt n.
I'll just throw the code here and we'll go over the lines one by one.
def getkthFactorOfN(n, k): i = 1 factors_asc = [] factors_desc = [] while i * i <p>Oof, it's way more complex. Let's break it down:</p> <p>First, we initialize i = 1. This variable will be used as the "number we're currently at" while searching for factors.</p> <p>Second, we'll create two arrays: factors_asc and factors_desc. The magic here is that we are going to add factors to factors_asc - they're named like this because they'll be automatically in ascending order.<br> Whenever we add something to factors_asc, we'll divide n by it and add it to factors_desc. Similar logic here; they'll be conveniently added in descending order.</p><p>Then, we begin our loop. Here I've changed it to be while i * i </p><p>We begin by checking if the current number is a factor (n % i == 0). If so, we can append it to our factors_asc array.</p> <p>Next, we get the "reverse factor" of i. We can do this by checking if i != n // i, or in other words, if it is not the root. This is because the root must not be duplicated in both arrays. If it isn't, we get the reversed factor by running n // i and appending the result in factors_desc.</p> <p>After that, we add 1 to i and continue our loop.</p> <p>After the loop is done, we must have every factorial we need.</p> <p>We begin by checking if k is in the first half including the root (which can be interpreted as the middle) with if k </p><p>If not, we must subtract the amount of factors found from k and check again - with k -= len(factors_asc) and if k </p><p>If k is inside factors_desc, get its value with factors_desk[-k] (from last to first).</p> <p>If all fails, return -1.</p> <h2> The curve </h2> <p>If you're wondering where in the curves graph it lands, it would be between <strong>O(n)</strong> and <strong>O(log n)</strong>, being better than the former and worse than the latter. Here's a graph:</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173598658415895.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="The Kth factor of N - an O(sqrt n) algorithm"><br> <em>Available at Mathspace</em></p> <h2> Conclusion </h2> <p>This was a ride to uncover and research. Thank you so much for reading up to this point.</p> <p>If you want to be more optimized, you can create factors_asc_len and factors_desc_len variables and add 1 every time you append a value to these arrays, so that the method len() doesn't have to be called, since this method is <strong>O(n)</strong> so it can impact time notation.</p> <p>Good luck in your studies and until next time!</p>
The above is the detailed content of The Kth factor of N - an O(sqrt n) algorithm. For more information, please follow other related articles on the PHP Chinese website!

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
