Tutorialspoint
Problem
Solution
Submissions

Perfect Square

Certification: Basic Level Accuracy: 100% Submissions: 2 Points: 5

Write a C# program that determines whether a given integer is a perfect square. A perfect square is an integer that is the square of another integer. For example, 16 is a perfect square because it's 4², and 25 is a perfect square because it's 5².

Example 1
  • Input: num = 16
  • Output: true
  • Explanation:
    • Step 1: Check if the number is negative (it's not).
    • Step 2: Calculate the square root of 16, which is 4.
    • Step 3: Check if the square root is an integer by comparing 4² with 16.
    • Step 4: Since 4² = 16, the number 16 is a perfect square.
Example 2
  • Input: num = 14
  • Output: false
  • Explanation:
    • Step 1: Check if the number is negative (it's not).
    • Step 2: Calculate the square root of 14, which is approximately 3.74.
    • Step 3: Check if the square root is an integer by comparing 3² with 14.
    • Step 4: Since 3² = 9, which is not equal to 14, the number is not a perfect square.
Constraints
  • 0 ≤ num ≤ 2³¹ - 1
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
NumberControl StructuresPwCSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Calculate the square root of the number using built-in functions
  • Check if the square root is an integer by comparing the square of its integer value with the original number
  • Alternatively, you can use binary search to find the square root
  • Remember to handle edge cases like 0 and 1
  • Consider potential overflows for large numbers

Steps to solve by this approach:

 Step 1: Handle edge cases (negative numbers, 0, and 1).
 Step 2: Initialize binary search boundaries (1 to num/2).
 Step 3: Perform binary search to find potential square root.
 Step 4: Compare the square of the mid value with the input number.
 Step 5: Return true if exact square root found, false otherwise.

Submitted Code :