Tech Number In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Tech Number In C++

Tech Number In C++

BLUF: Mastering Tech Number In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Tech Number In C++

C++ is renowned for its efficiency. Learn how Tech Number In C++ enables low-level control and high-performance computing in the tutorial below.

Introduction

A Tech Number is a concept that has been analyzed mathematically, often applied in programming to address specific challenges or issues. While not a conventional concept in mathematics or computer science, it is commonly employed in competitive programming and coding tasks to describe numbers with unique numerical characteristics. The notion of a Tech Number revolves around selecting numbers that meet certain criteria based on the manipulation of their digits through various operations.

Tech Number is defined as a number that meets the following criteria:

  • Even Number of Digits: The number of digits in the number should be an even count. It is necessary because we need to split the number in two halves equal and verify these properties.
  • Splitting into Equal Halves: It is broken into two equal parts. A simple example is a four-digit number like 2025 is split into 20 and 25. If the number had six digits, it would be decomposed into three-digit parts, and so on.
  • Sum of Halves: So once the number is split into two halves they are added together. In order for the next step, verification, this is the sum of these halves.
  • Squared Sum Matches the Original Number: We calculate the square of the sum of two halves. A Tech Number is a number that, when squared, gives the same result as the original.

To provide an illustration, let's suppose 2025 is a numerical value. It consists of four digits, an even quantity, enabling it to be divided into two equal parts: 20 and 25. Upon adding these two parts, the result is 20 + 25 = 45. By squaring this total, 45² = 2025, verifying that the initial number is indeed a Tech Number.

Applications and Relevance:

  • Understanding Mathematical Patterns: Searching and working with specific numerical properties helps programmers understand mathematics better and its practical applications.
  • Digit Manipulation: Tech Numbers help to build expertise in handling individual digits of a number as well as string slicing, arithmetic operations, and type conversions that we often come across in programming challenges.
  • Debugging and Testing: As a part of working with Tech Numbers, we get to handle edge cases, testing the robustness of the logic implemented, for example, dealing with input that doesn't fit certain criteria or has an odd number of digits.
  • Challenges in Implementation:

  • Performance Optimization: The logic is simple but processing large number or many inputs is difficult in the environments where we compete in competitive programming. However, scaling the algorithm well with input size is an important consideration.
  • Edge Cases: We need to support special cases like single-digit numbers, negative numbers, or numbers really big, etc. For scenarios like this, implementing can become complicated, and can have some additional checks required in our logic.
  • Approach-1: Basic Arithmetic Approach

The fundamental Arithmetic Method, utilized to determine a Technical Value, requires performing arithmetic operations on the number using the / and % operators to divide the number in half while maintaining its numerical form. Rather than converting it to a string, the process begins by determining the necessary number of digits and the specific digit count required, followed by splitting the number based on powers of 10.

It computes the total of the divided halves and then checks it against the square of the initial number. When there's a match, the number qualifies as a Tech Number. This approach is effective with small inputs as it eliminates the need for string operations, making it ideal for arithmetic-centric programming tasks. Nonetheless, managing extensive numbers or unique scenarios can present challenges with this method.

Example:

Let's consider an example to demonstrate the Tech number using fundamental arithmetic methods in C++.

Example

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
// Function to count the digits in a number
int countDigits(int num) {
    int count = 0;
    while (num > 0) {
        count++;
        num /= 10;
    }
    return count;
}
// Function to calculate the power of 10 (used for splitting the number)
int powerOf10(int exp) {
    int result = 1;
    for (int i = 0; i < exp; i++) {
        result *= 10;
    }
    return result;
}
// Function to validate user input
bool isValidInput(int num) {
    if (num < 0) {
        cout << "Negative numbers cannot be Tech Numbers.\n";
        return false;
    }
    if (countDigits(num) % 2 != 0) {
        cout << "Number must have an even number of digits.\n";
        return false;
    }
    return true;
}
// Function to check if a number is a Tech Number
bool isTechNumber(int num) {
    if (!isValidInput(num)) return false;
    int digits = countDigits(num);
    // Split the number into two halves
    int halfDigits = digits / 2;
    int divisor = powerOf10(halfDigits);
    int firstHalf = num / divisor;  // Extract the first half
    int secondHalf = num % divisor; // Extract the second half
    // Calculate the sum of the two halves
    int sum = firstHalf + secondHalf;
    // Check if the square of the sum equals the original number
    return (sum * sum == num);
}
// Function to get a list of Tech Numbers in a given range
vector<int> findTechNumbersInRange(int start, int end) {
    vector<int> techNumbers;
    for (int i = start; i <= end; i++) {
        if (isTechNumber(i)) {
            techNumbers.push_back(i);
        }
    }
    return techNumbers;
}
// Function to test predefined examples
void testPredefinedExamples() {
    cout << "\nTesting predefined examples:\n";
    vector<int> examples = {2025, 3025, 9801, 1234, 1001, 123321, 4096};
    for (int num : examples) {
        cout << num << " -> ";
        if (isTechNumber(num)) {
            cout << "Tech Number\n";
        } else {
            cout << "Not a Tech Number\n";
        }
    }
}
// Function to test user-defined range
void testUserDefinedRange() {
    int start, end;
    cout << "\nEnter a range to find Tech Numbers (start and end): ";
    cin >> start >> end;
    if (start > end) {
        cout << "Invalid range. Start must be less than or equal to end.\n";
        return;
    }
    vector<int> techNumbers = findTechNumbersInRange(start, end);
    cout << "\nTech Numbers in the range " << start << " to " << end << ":\n";
    if (techNumbers.empty()) {
        cout << "No Tech Numbers found in the given range.\n";
    } else {
        for (int num : techNumbers) {
            cout << num << " ";
        }
        cout << endl;
    }
}
// Function to check a single number input by the user
void checkSingleNumber() {
    int num;
    cout << "\nEnter a number to check if it's a Tech Number: ";
    cin >> num;
    if (isTechNumber(num)) {
        cout << num << " is a Tech Number.\n";
    } else {
        cout << num << " is NOT a Tech Number.\n";
    }
}
// Main function
int main() {
    cout << "Welcome to the Tech Number Checker Program!\n";
    // Test predefined examples
    testPredefinedExamples();
    // Check a single number
    checkSingleNumber();
    // Test for a range of numbers
    testUserDefinedRange();
    cout << "\nThank you for using the Tech Number Checker Program. Goodbye!\n";
    return 0;
}

Output:

Output

Welcome to the Tech Number Checker Program!
Testing predefined examples:
2025 -> Tech Number
3025 -> Tech Number
9801 -> Tech Number
1234 -> Not a Tech Number
1001 -> Not a Tech Number
123321 -> Not a Tech Number
4096 -> Not a Tech Number
Enter a number to check if it's a Tech Number: 3025
3025 is a Tech Number.
Enter a range to find Tech Numbers (start and end): 2000 5000
Tech Numbers in the range 2000 to 5000:
2025 3025 
Thank you for using the Tech Number Checker Program. Goodbye!

Explanation:

countDigits:

  • This function loops the number for digits within number.
  • Example: For 2025, the digit count is 4.
  • We know that the number has an even number of digits, but we somehow need to find out.

powerOf10:

  • The function divides numbers based on 10 raised to different powers.
  • For instance, considering powerOf10(n), it calculates n times the power of 10. This calculation allows splitting a 4-digit number like 2025 into two halves: 2n (the first half) and (2n+1) (the second half).

isValidInput:

  • Validates the input for a Tech Number by confirming it meets specific criteria. The input must be a non-negative number with an even number of digits. Only valid inputs, such as positive numbers with an even number of digits, are accepted. Any inputs that do not meet these criteria will trigger relevant error messages.

isTechNumber:

The fundamental logic for recognizing a Technical Number.

Validates the provided input.

  • The division operation (using the slash /) and the modulus operation (using the percent sign) are used to separate a number into two halves. These two halves are then added together, and the resulting sum is checked to see if its square is equal to the original number.
  • For instance, consider the number 2025. Dividing it into 20 and 25, we get 20 + 25 = 45. By squaring 45, we find (45)^2 = 2025, confirming it as a Tech Number.

IterateThroughTechNumbersInRange:

  • Traverse a custom-defined range to discover all the Technical Numbers within it.
  • For instance: Detect 2025, 3025, and 9801 within the interval 2000-10000.
  • This demonstrates the accuracy of the software through predefined test cases.

testUserDefinedRange:

  • Individuals are able to specify a custom range to retrieve Tech Numbers and manage incorrect ranges effectively.
  • Complexity Analysis:

Time Complexity

countDigits(int num)

The countDigits function iterates until the number reaches 0. Initially, the number undergoes division by reducing it with each step, and the number of iterations is directly related to the number of digits, denoted as 'd', in the given number.

It is evident that the time complexity of the countDigits function is O(log10(n)) because the number of digits, d, is O(log10(n)) for the input number n.

The function powerOf10(int exp) utilizes a loop to calculate 10 raised to the power of exp. The number of iterations in the loop is determined by the value of exp, which is usually half of the number of digits in the number being processed. Hence, the time complexity of powerOf10 is O(d) or O(log10(n)), where d is the number of digits in the input number.

The isTechNumber function determines whether a given number is a technical number. The countDigits method calculates the number of digits in the input number, with a time complexity of O(log10(n)). Following this, it calculates the power of 10 to split the number (powerOf10), with a time complexity of array d. All remaining operations such as squaring, dividing, and adding are considered O(1) operations.

Therefore, the total time complexity of the isTechNumber function can be expressed as O(log10(n)) + O(d), which simplifies to O(d) = O(log10(n)).

findTechNumbersInRange(int end, int start)

  • This function takes a range from start to end and does its loop over that range calling isTechNumber for each number.
  • The isTechNumber function has a time complexity of O(log10(n)) for each number in the range.
  • As a result, the time complexity is O( k log_10 (n) ), where n is the average of the value in the range.

testPredefinedExamples

  • This method will loop over a set of specified constant values and verify if it qualifies as a Technology Number by utilizing the isTechNumber function.
  • The computational complexity is O(m log10 n) where m represents the quantity of test scenarios and n denotes the typical number of test cases within the collection. Both m and n remain fixed at a specific list magnitude.

Space Complexity

calculateDigits(int num):

The function countDigits(int num) operates with a fixed amount of memory, storing solely the number itself and a counter variable. Its space complexity is O(1).

The function employs iteration to calculate powers of 10 and retain the outcome, yet retains whatever the output was. It maintains a constant space complexity of O(1) as well.

The function requires a fixed number of variables to store different parts of the number, such as the two halves, their sum, and their squares. This allows the function to be implemented in constant space complexity, denoted as O(1).

This function examines a specified range for Tech Numbers and saves them in a vector data structure. The space complexity of this operation is directly related to the quantity of Tech Numbers within the range. In the most extreme scenario, the space complexity reaches O(k), with 'k' representing the range's magnitude.

Other Operations:

The functions testPredefinedExamples and checkSingleNumber are examples of functions with a space complexity of O(1), as they only require storage for a small number of variables.

Approach-2: Recursive Approach

The Recursive Method for verifying a number as a Technology Number integrates the concept of recursion and divide-and-conquer strategy. The fundamental concept involves iteratively dividing the number into two parts and evaluating the sum of these parts to determine if the square of the sum matches the original number. This technique involves invoking a function recursively to partition the number into smaller segments until a base scenario of a single-digit number is attained.

The value undergoes division by two in each iteration, and subsequently, the sum of these divisions is calculated. This iterative process continues until reaching a point where the number reduces to one, allowing for a direct comparison with the original number. Leveraging a recursive methodology not only simplifies the code significantly but also provides an elegant solution to the problem. While recursion is beneficial for illustrative purposes, its efficiency may diminish when dealing with larger numerical values.

Example:

Let's consider a scenario to demonstrate the Tech number using a recursive method in C++.

Example

#include <iostream>
#include <cmath>
using namespace std;
// Function to count the number of digits in a number
int countDigits(int num) {
    int count = 0;
    while (num > 0) {
        count++;
        num /= 10;
    }
    return count;
}
// Recursive function to check if a number is a Tech Number
bool isTechNumberHelper(int num, int totalDigits, int digitCount) {
    // Base case: if we reach a single digit, return false since we need two halves
    if (digitCount == 1) {
        return false;
    }
    // Get the power of 10 for the second half (half the total number of digits)
    int powerOf10 = pow(10, totalDigits / 2);
    // Split the number into two halves
    int firstHalf = num / powerOf10;
    int secondHalf = num % powerOf10;
    // Calculate the sum of the halves
    int sum = firstHalf + secondHalf;

    // Check if the square of the sum equals the original number
    if (sum * sum == num) {
        return true;
    }
    // Recursive case: if not a Tech Number, recursively try with fewer digits
    return isTechNumberHelper(num / 10, totalDigits, digitCount - 1);
}
// Wrapper function to handle the recursion and start checking Tech Number
bool isTechNumber(int num) {
    // Base case: handle negative or single-digit numbers
    if (num < 10) {
        return false;
    }
    // Count the digits
    int digitCount = countDigits(num);
    // Check if the number has an even number of digits
    if (digitCount % 2 != 0) {
        return false;
    }
    // Call the recursive helper function
    return isTechNumberHelper(num, digitCount, digitCount);
}
// Function to find Tech Numbers in a range
void findTechNumbersInRange(int start, int end) {
    cout << "Tech Numbers between " << start << " and " << end << " are: " << endl;
    for (int i = start; i <= end; i++) {
        if (isTechNumber(i)) {
            cout << i << " ";
        }
    }
    cout << endl;
}
// Test predefined examples for Tech Numbers
void testPredefinedExamples() {
    int numbers[] = {2025, 3025, 1234, 9, 9999, 12321};
    cout << "Testing predefined numbers:" << endl;
    for (int i = 0; i < 6; i++) {
        if (isTechNumber(numbers[i])) {
            cout << numbers[i] << " is a Tech Number." << endl;
        } else {
            cout << numbers[i] << " is not a Tech Number." << endl;
        }
    }
}
// Function to test a single number entered by the user
void checkSingleNumber() {
    int num;
    cout << "Enter a number to check if it's a Tech Number: ";
    cin >> num;
    if (isTechNumber(num)) {
        cout << num << " is a Tech Number." << endl;
    } else {
        cout << num << " is not a Tech Number." << endl;
    }
}
int main() {
    int choice;
    do {
        cout << "\nTech Number Check Program\n";
        cout << "1. Check if a single number is a Tech Number\n";
        cout << "2. Find Tech Numbers in a range\n";
        cout << "3. Test predefined examples\n";
        cout << "4. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;
        switch (choice) {
            case 1:
                checkSingleNumber();
                break;
            case 2:
                int start, end;
                cout << "Enter the range (start end): ";
                cin >> start >> end;
                findTechNumbersInRange(start, end);
                break;
            case 3:
                testPredefinedExamples();
                break;
            case 4:
                cout << "Exiting program.\n";
                break;
            default:
                cout << "Invalid choice, please try again.\n";
        }
    } while (choice != 4);

    return 0;
}

Output:

Output

Tech Number Check Program
1. Check if a single number is a Tech Number
2. Find Tech Numbers in a range
3. Test predefined examples
4. Exit
Enter your choice: 1
Enter a number to check if it's a Tech Number: 2025
2025 is a Tech Number.
Tech Number Check Program
1. Check if a single number is a Tech Number
2. Find Tech Numbers in a range
3. Test predefined examples
4. Exit
Enter your choice: 2
Enter the range (start end): 2000
5000
Tech Numbers between 2000 and 5000 are: 
2025 3025 
Tech Number Check Program
1. Check if a single number is a Tech Number
2. Find Tech Numbers in a range
3. Test predefined examples
4. Exit
Enter your choice: 4
Exiting program.

Explanation:

The process commences with a function designed to count the digits within a number, enabling the number to be evenly divided into two parts. Following this initial step, the isTechNumberHelper function is introduced to execute a recursive method for verifying whether the number qualifies as a Tech Number. Within this function, the number is divided into two equal halves, with each half calculated separately using mathematical operations like division and modulo calculation.

Afterward, it computes the total of these two partitions. If the square of this total matches the specified number, it qualifies as a fortunate number. In such a case, the function will yield true, confirming the number as a Tech Number. Conversely, if the criteria are not satisfied, the function will trigger a recursive process. This recursive approach involves breaking down the number into smaller digit groupings and decrementing them one by one until reaching the base scenario of a single digit. At this point, the function will output false.

The primary function named isTechNumber functions as a wrapper to verify whether a number possesses an even number of digits, triggering a recursive helper function if the condition is met. Conversely, the number is promptly disqualified as a Tech Number if it contains an odd number of digits.

Following this, individuals have the option to utilize an intuitive interface to verify whether a specific number qualifies as a Technology Number, locate all Technology Numbers within a specified range, and examine predefined instances. This software enables the validation of single numbers and ranges by accepting both input types and conducting the necessary assessments. A series of predetermined examples assess a variety of numbers to determine their status as Technology Numbers. The program operates in a loop, allowing users to perform multiple checks until they choose to terminate the process.

The method employs a recursive strategy to address the issue, gradually breaking it down into smaller parts with each iteration. However, the drawback of numerous recursive invocations can hinder its performance, especially when dealing with substantial data sets.

Complexity Analysis:

Time Complexity:

  • In this case, the recursive approach has an already known time complexity that majorly depends on the number of digits in the input number. Let the number have d digits.
  • The countChars function runs in O(d), where d is the number of digits in the number. As mentioned, it takes a sequence of digits and iterates it once to find the total number of numbers in each number.
  • Recursively, the isTechNumberHelper function splits the number into two halves. As the number is divided by two recursively, it's no longer written in base 10. It means that its recursion depth is proportional to the number of digits, O(d).
  • At each recursive level, the function performs constant-time operations: We can calculate the sum of two halves and check if the square of the sum equals the original number in O(1) time.
  • The overall time complexity is O(d) due to the fact that the recursion depth is directly proportional to the number of digits, and each recursive step will take constant work time.

Space Complexity:

The space usage is determined by two primary aspects:

  • It depends on the depth, denoted as d, which corresponds to the number of digits in the input. This results in a space complexity of O(d) for recursion.
  • On the other hand, the additional space required remains constant as there are no data structures like arrays or lists utilized.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience