
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of Square Numbers in C++
Suppose we have a non-negative integer c, we have to decide whether there're two integers a and b such that it satisfies a^2 + b^2 = c.
So, if the input is like 61, then the output will be True, as 61 = 5^2 + 6^2.
To solve this, we will follow these steps −
Define a function isPerfect(), this will take x,
sr := square root of x
return true when (sr - floor of sr) is 0
From the main method do the following,
-
if c is same as 0, then −
return true
-
for initialize i := 0, when i < the ceiling of square root of c, update (increase i by 1), do −
b := c - i * i
-
if isPerfect(b) is true, then −
return true
return false
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool isPerfect(int x){ long double sr = sqrt(x); return ((sr - floor(sr)) == 0); } bool judgeSquareSum(int c) { if (c == 0) return true; int b; for (int i = 0; i < ceil(sqrt(c)); i++) { b = c - i * i; if (isPerfect(b)) return true; } return false; } }; main(){ Solution ob; cout << (ob.judgeSquareSum(61)); }
Input
61
Output
1
Advertisements