Squares of Numbers with Repeated Single Digits


What is the question `Square of numbers with repeated single digits` asking us to do? Let’s decode!

The problem "Squares of numbers with repeated single digits" aims to find the square of numbers like 33, 44, 555, etc which contains repeated single digits.

Approach 1: Naive Approach

We can use the naive approach to calculate the square of numbers, which includes the following steps:

  • Take the numbers as input

  • Use the multiplication operator to calculate the square i.e square_of_number= number * number

  • then print the result

Implementation in C++

Here is the implementation of above approach

Example

#include <iostream>

using namespace std;

int main() {
    int num = 333;
    // input the number
    long long res = num * num; // calculate the square
    cout << "The square of " <<num<< " is =" <<res << endl; // output the result
    return 0;
}

Output

The square of 333 is =110889

Time Complexity: O(1)

Space Complexity: O(1)

Approach 2: Writing as Multiples of 1111…1

  • Every such number can be represented as a multiple of 1111…1. For example, 33333 = 3 * 11111.

  • The squares of 11, 111, 1111, 11111 … are 121, 12321, 1234321, 123454321, etc.

  • For calculating the squares of 11,111,.. we have a pattern. Check this link.

  • So a simple solution is to find the square of 111…11 and then multiply the result with 3 ,4,5,6, etc (depending on the repeating digit).

  • We can use multiplication with large numbers to get the final result.

Code Implementation

Example

#include <iostream>
#include <cmath>
using namespace std;


long long square_of_ones(int num) {
     int n = log10(num) + 1; 
   long long square = 0; 
   for (int i = 1; i <= n; i++) {
      square= square* 10 + i;
   }
   for (int i = n - 1; i >= 1; i--) {
      square= square* 10 + i;
   }
   return square;
}

int main() {
    int num = 44;
    
    long long res = square_of_ones(num); // calculate the square
    int last_digit = num % 10;
    cout << "The square of " <<num<< " is =" <<res * last_digit * last_digit<< endl; // output the result
    return 0;
}

Output

The square of 44 is =1936

Time Complexity : O(n)

Space Complexity : O(1)

Conclusion

In this article, we have tried to explain the approach to calculating the square of numbers with repeated single digits using two different approaches. I hope this article helps you to grasp the concept behind the calculation in a better way.

Updated on: 23-Aug-2023

47 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements