Programmer's algorithm interesting question Q12: square root number

Posted by albinoazn on Thu, 16 Dec 2021 19:33:30 +0100

catalogue

1. Problem description

2. Problem solving analysis

3. Code and test

1. Problem description

Find the smallest integer that makes all the numbers from 0 to 9 appear at the earliest time when calculating the square root. Note that only the case where the square root is a positive number is required here, and please find the case where the integer part is included and the case where the decimal part is only looked at.

Example) square root of 2: 1.414213562373095048 (19 bits are required for all occurrences of 0 ~ 9)

2. Problem solving analysis

This topic is rather vague.

In fact, it is the smallest integer that finds the first ten digits of the square root (with or without integer part) so that all the numbers from 0 to 9 appear (and do not repeat) - that is, it constitutes a permutation from 0 to 9.

The key is that the topic requires both "earliest" and "minimum".

Assuming that you traverse from small to large according to the natural number, you can be sure that you have found the smallest integer that meets the problem conditions only when you find a number whose first ten digits of the square root just make all the numbers from 0 to 9 appear.

Before you find the number that satisfies "the first ten digits of the square root just make all the numbers from 0 to 9 appear", you can't determine whether there is a number that satisfies "the first ten digits of the square root just make all the numbers from 0 to 9 appear", so you can only keep looking.

Fortunately, the number satisfying "the first ten digits of the square root just make all the numbers from 0 to 9 appear" exists.

The basic steps are as follows:

Traverse natural number from small to large:

For each natural number:

Find its square root

Convert to string

Take the first ten characters (characters other than the decimal point), or take the first ten characters after the decimal point

Judge whether these ten characters contain all 0 ~ 9 exactly

Exit if the conditions are met, otherwise continue to search for the next one

In the code, use the following to judge whether the first ten characters meet the problem setting conditions:

len(set(list(first10))) == 10

This is because set will automatically delete duplicate elements. Therefore, if the length of set is 10 and its possible elements can only be 0 ~ 9, the condition must be met.

3. Code and test

# -*- coding: utf-8 -*-
"""
Created on Sat Sep  4 08:51:51 2021

@author: chenxy
"""

import sys
import time
import datetime
import math
# import random
from   typing import List
# from   queue import Queue
# from   collections import deque

class Solution:
    def squareRoot1(self, sel:int) -> tuple:
        """
        Find the first interger, for which, either the first 10 digits of its square root, 
        or the first 10 digits of the decimal part of its square root, 
        includes all of 0~9.
        
        sel:  0--including integer part; 1: not including integer part
        :ret: The total number of IP satisfying the requirement
        """                
        i = 1
        while(1):
            i_sqrt = math.sqrt(i)
            i_sqrt_str = str(i_sqrt)

            # Find the position of decimal point
            for k in range(len(i_sqrt_str)):
                if i_sqrt_str[k] == '.':
                    break            
                
            if sel == 0:
                first10 = i_sqrt_str[0:k] + i_sqrt_str[k+1:11]
            else:
                first10 = i_sqrt_str[k+1:k+11]
                # print(first10,list(first10),set(list(first10)))
            
            if len(set(list(first10))) == 10:
                return i, i_sqrt
            
            i = i+1
                    
if __name__ == '__main__':        
            
    sln    = Solution()            
    
    tStart = time.time()
    num1,num1_sqrt = sln.squareRoot1(0)
    num2,num2_sqrt = sln.squareRoot1(1)
    tCost  = time.time() - tStart
    print('num1={0}, num1_sqrt={1:.10f}, tCost = {1:6.3f}(sec)'.format(num1,num1_sqrt,tCost))    
    print('num2={0}, num2_sqrt={1:.10f}, tCost = {1:6.3f}(sec)'.format(num2,num2_sqrt,tCost))  

Operation results:

        num1=1362, num1_sqrt=36.9052841745, tCost =  0.002(sec)
        num2=143, num2_sqrt=11.9582607431, tCost =  0.002(sec)

Previous: Q11: Fibonacci sequence

Next:

For the general catalogue of this series, see: Programmer's interesting algorithm: detailed analysis and Python complete solution

Topics: Python Algorithm