- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Sum of square of first n odd numbers
- Sum of square-sums of first n natural numbers
- Squared and square rooted sum of numbers of an array in JavaScript
- Difference between sum of square and square of sum in JavaScript
- Difference between sum of the squares of and square of sum first n natural numbers.
- Sum of sum of first n natural numbers in C++
- Count square and non-square numbers before n in C++
- Sum of two large numbers in C++
- PHP program to calculate the sum of square of first n natural numbers
- Sum of squares of Fibonacci numbers in C++
- Print the Non Square Numbers in C
- Consecutive Numbers Sum in C++
- Count of numbers satisfying m + sum(m) + sum(sum(m)) = N in C++
- Sum of two numbers modulo M in C++
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++

Advertisements