Open In App

Mid-Square hashing

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Mid-Square hashing is a hashing technique in which unique keys are generated. In this technique, a seed value is taken and it is squared. Then, some digits from the middle are extracted. These extracted digits form a number which is taken as the new seed. This technique can generate keys with high randomness if a big enough seed value is taken. However, it has a limitation. As the seed is squared, if a 6-digit number is taken, then the square will have 12-digits. This exceeds the range of int data type. So, overflow must be taken care of. In case of overflow, use long long int data type or use string as multiplication if overflow still occurs. The chances of a collision in mid-square hashing are low, not obsolete. So, in the chances, if a collision occurs, it is handled using some hash map. Example:

Suppose a 4-digit seed is taken. seed = 4765 Hence, square of seed is = 4765 * 4765 = 22705225 Now, from this 8-digit number, any four digits are extracted (Say, the middle four). So, the new seed value becomes seed = 7052 Now, square of this new seed is = 7052 * 7052 = 49730704 Again, the same set of 4-digits is extracted. So, the new seed value becomes seed = 7307 . . . . This process is repeated as many times as a key is required.

Mid square technique takes a certain number of digits from the square of a number. This number extracted is a pseudo-random number, which can be used as a key for hashing. Algorithm:

  1. Choose a seed value. This is an important step as for same seed value, the same sequence of random numbers is generated.
  2. Take the square of the seed value and update seed by a certain number of digits that occur in the square. Note: The larger is the number of digits, larger will be the randomness.
  3. Return the key.

Below is the implementation of above algorithm: 

CPP
// C++ program to illustrate the
// mid-square hashing technique
#include <ctime>
#include <iostream>

using namespace std;

// Returns a seed value based on current system time.
long long int newTime()
{

    // Acquiring number of seconds
    // passed from Jan 1, 1970.
    time_t t = time(NULL);

    // Converting the time to year, month,
    // day, hour, minute, and second.
    struct tm* tm = localtime(&t);
    long long int x;

    // Applying a certain logic to get
    // required number of digits. It may vary.
    x = (tm->tm_hour) * 10000000 + (tm->tm_min) * 100000
        + (tm->tm_sec) * 1000 + (tm->tm_mday) * 10 + (tm->tm_year);

    // Return the calculated number.
    return x;
}

// Returns a random 8-digit key.
long int getKey()
{

    // Taking the key from system time. 
    // returns a  8-digit seed value.
    static long long int key = newTime();

    // Squaring the key.
    key = key * key;

    // Extracting required number of digits ( here, 8 ).
    if (key < 1000000000000000) {
        key = key / 10000;
        key = key % 100000000;
    }
    else {
        key = key / 10000;
        key = key % 100000000;
    }

    // Returning the key value.
    return key;
}

// Driver Code
int main()
{
    // get the first key
    std::cout << getKey() << endl;

    // get the second key
    std::cout << getKey() << endl;
    return 0;
}

//Note: The output will change according to the date and time.
Java
import java.time.LocalDateTime;

public class Main {
    
    // Returns a seed value based on current system time.
    public static long newTime() {
        // Acquiring the current date and time
        LocalDateTime now = LocalDateTime.now();
        
        // Extracting components: hour, minute, second, day, and year
        long x = now.getHour() * 10000000 + now.getMinute() * 100000 +
                 now.getSecond() * 1000 + now.getDayOfMonth() * 10 + now.getYear();
        
        // Return the calculated seed value
        return x;
    }

    // Returns a random 8-digit key.
    public static long getKey() {
        // Taking the key from system time to generate a seed value
        long key = newTime();
        
        // Squaring the key
        key = key * key;

        // Extracting required number of digits (here, 8).
        if (key < 1000000000000000L) {
            key = key / 10000;
            key = key % 100000000;
        } else {
            key = key / 10000;
            key = key % 100000000;
        }

        // Returning the key value
        return key;
    }

    // Driver Code
    public static void main(String[] args) {
        // Get the first key
        System.out.println(getKey());
        
        // Get the second key
        System.out.println(getKey());
    }
}
//Note: The output will change according to the date and time.
C#
using System;

namespace MidSquareHashing
{
class Program
{
// Returns a seed value based on current system time.
static long newTime()
{
// Acquiring number of seconds
// passed from Jan 1, 1970.
long t = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

        // Converting the time to year, month,
        // day, hour, minute, and second.
        DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        dtDateTime = dtDateTime.AddSeconds(t).ToLocalTime();
        long x;

        // Applying a certain logic to get
        // required number of digits. It may vary.
        x = (dtDateTime.Hour) * 10000000 + (dtDateTime.Minute) * 100000
            + (dtDateTime.Second) * 1000 + (dtDateTime.Day) * 10 + (dtDateTime.Year);

        // Return the calculated number.
        return x;
    }

    // Returns a random 8-digit key.
    static long getKey()
    {
        // Taking the key from system time.
        // returns a 8-digit seed value.
        long key = newTime();

        // Squaring the key.
        key = key * key;

        // Extracting required number of digits ( here, 8 ).
        if (key < 1000000000000000)
        {
            key = key / 10000;
            key = key % 100000000;
        }
        else
        {
            key = key / 10000;
            key = key % 100000000;
        }

        // Returning the key value.
        return key;
    }

    // Driver Code
    static void Main(string[] args)
    {
        // get the first key
        Console.WriteLine(getKey());

        // get the second key
        Console.WriteLine(getKey());
    }
}
}

//Note: The output will change according to the date and time.
JavaScript
// Returns a seed value based on current system time.
function newTime() {
    // Acquiring the current date and time
    const now = new Date();
    
    // Extracting components: hour, minute, second, day, and year
    let x = now.getHours() * 10000000 + now.getMinutes() * 100000 +
             now.getSeconds() * 1000 + now.getDate() * 10 + now.getFullYear();
    
    // Return the calculated seed value
    return x;
}

// Returns a random 8-digit key.
function getKey() {
    // Taking the key from system time to generate a seed value
    let key = newTime();
    
    // Squaring the key
    key = key * key;

    // Extracting required number of digits (here, 8).
    if (key < 1000000000000000) {
        key = Math.floor(key / 10000) % 100000000;
    } else {
        key = Math.floor(key / 10000) % 100000000;
    }

    // Returning the key value
    return key;
}

// Driver Code
// Get the first key
console.log(getKey());

// Get the second key
console.log(getKey());
Python3
import time

# Returns a seed value based on current system time.
def new_time():
    # Acquiring number of seconds passed since Jan 1, 1970.
    t = int(time.time())
    
    # Converting the time to year, month, day, hour, minute, and second.
    tm = time.localtime(t)
    
    # Applying a certain logic to get required number of digits.
    x = (tm.tm_hour) * 10000000 + (tm.tm_min) * 100000 + (tm.tm_sec) * 1000 + (tm.tm_mday) * 10 + (tm.tm_year)
    
    # Return the calculated number.
    return x

# Returns a random 8-digit key.
def get_key():
    # Taking the key from system time. 
    # Returns an 8-digit seed value.
    global key
    key = new_time()

    # Squaring the key.
    key *= key

    # Extracting required number of digits (here, 8).
    if key < 1000000000000000:
        key //= 10000
        key %= 100000000
    else:
        key //= 10000
        key %= 100000000

    # Returning the key value.
    return key

# Driver Code
if __name__ == "__main__":
    # Get the first key
    print(get_key())
    
    # Get the second key
    print(get_key())
    
 #Note: The output will change according to the date and time.

Output
24788668
47806121

Note: The output will change according to the date and time.



Similar Reads

Area of the largest square that can be formed from the given length sticks using Hashing
Given an array arr[] of N integers representing the heights of the sticks. The task is to find the area of the largest square that can be formed using these sticks and the count of such squares. Note that a single side of the square can only use a single stick.Examples: Input: arr[] = {5, 3, 2, 3, 6, 3, 3} Output: Area = 9 Count = 1 Side of the squ
6 min read
Program to find the mid-point of a line
Given two coordinates of a line starting is (x1,y1) and ending is (x2,y2) find out the mid-point of a line. Examples : Input : x1 = –1, y1 = 2, x2 = 3, y2 = –6 Output : 1,–2 Input : x1 = 6.4, y1 = 3 x2 = –10.7, y2 = 4 Output : –2.15, 3.5 The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the point M found by the following fo
3 min read
Find the other end point of a line with given one end and mid
Given a midpoint of line(m1, m2) and one coordinate of a line (x1, y1), find the other end point(x2, y2) of a line. Examples: Input : x1 = –1, y1 = 2, and m1 = 3, m2 = –6 Output : x2 = 7, y2 = 10 Input : x1 = 6.4, y1 = 3 and m1 = –10.7, m2 = 4 Output : x2 = 3, y2 = 4 The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the poi
4 min read
Find the Mid-Alphabet for each index of the given Pair of Strings
Given two same-length strings str1 and str2 consisting of lowercase English alphabets, the task is to find the Mid-Alphabet for each index of the given pair of Strings. Examples: Input: str1 = "abcd", str2 = "cdef" Output: bcde Explanation: b is mid of a and c c is mid of b and d d is mid of c and e e is mid of e and f Input: str1 = "akzbqzgw", str
4 min read
How to calculate "mid" or Middle Element Index in Binary Search?
The most common method to calculate mid or middle element index in Binary Search Algorithm is to find the middle of the highest index and lowest index of the searchable space, using the formula mid = low + \frac{(high - low)}{2} Is this method to find mid always correct in Binary Search? Consider the following implementation of the Binary Search fu
6 min read
Mid-Point Line Generation Algorithm
Given coordinate of two points A(x1, y1) and B(x2, y2) such that x1 &lt; x2 and y1 &lt; y2. The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.We have discussed below algorithms for this task. DDA algorithm for line drawingIntroduction to Bresenha
11 min read
Find Corners of Rectangle using mid points
Consider a rectangle ABCD, we're given the co-ordinates of the mid points of side AD and BC (p and q respectively) along with their length L (AD = BC = L). Now given the parameters, we need to print the co-ordinates of the 4 points A, B, C and D. Examples: Input : p = (1, 0) q = (1, 2) L = 2 Output : (0, 0), (0, 2), (2, 2), (2, 0) Explanation: The
11 min read
Count square and non-square numbers before n
Given a number n, we need to count square numbers smaller than or equal to n.Examples : Input : n = 5 Output : Square Number : 2 Non-square numbers : 3 Explanation : Square numbers are 1 and 4. Non square numbers are 2, 3 and 5. Input : n = 10 Output : Square Number : 3 Non-square numbers : 7 Explanation : Square numbers are 1, 4 and 9. Non square
5 min read
Program to print Square inside a Square
Given a number N, print a hollow square of side with N asterisks('*'), and inside it print a hollow square of side N-4 asterisks('*').Examples : Input : 6 Output : ****** * * * ** * * ** * * * ****** Input :9 Output : ********* * * * ***** * * * * * * * * * * * * * * ***** * * * ********* The idea is to run two nested loops from 1 to n for rows and
7 min read
Solid square inside a hollow square | Pattern
Given the value of n, print a hollow square of side length n and inside it a solid square of side length (n - 4) using stars(*). Examples : Input : n = 6 Output : ****** * * * ** * * ** * * * ****** Input : n = 11 Output : *********** * * * ******* * * ******* * * ******* * * ******* * * ******* * * ******* * * ******* * * * *********** C/C++ Code
5 min read
Article Tags :