- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = N) in C++
We are given a number N. The goal is to find ordered pairs of positive numbers such that the sum of their cubes is N.
We will do this by finding solutions to the equation a3 + b3 = N. Where a is not more than cube root of N and b can be calculated as cube root of (N-a3).
Let’s understand with examples.
Input
N=35
Output
Count of pairs of (a,b) where a^3+b^3=N: 2
Explanation
Pairs will be (2,3) and (3,2). 23+33=8+27=35
Input
N=100
Output
Count of pairs of (a,b) where a^3+b^3=N: 0
Explanation
No such pairs possible.
Approach used in the below program is as follows
We take integer N.
Function cubeSum(int n) takes n and returns the count of ordered pairs with sum of cubes as n.
Take the initial variable count as 0 for pairs.
Traverse using for loop to find a.
Start from a=1 to a<=cbrt(n) which is cube root of n.
Calculate cube of b as n-pow(a,3).
Calculate b as cbrt(bcube)
If pow(b,3)==bcube. Increment count by 1.
At the end of all loops count will have a total number of such pairs.
Return the count as result.
Example
#include <bits/stdc++.h> #include <math.h> using namespace std; int cubeSum(int n){ int count = 0; for (int a = 1; a < cbrt(n); a++){ int bcube=n - (pow(a,3)); int b = cbrt(bcube); if(pow(b,3)==bcube) { count++; } } return count; } int main(){ int N = 35; cout <<"Count of pairs of (a,b) where a^3+b^3=N: "<<cubeSum(N); return 0; }
Output
If we run the above code it will generate the following output −
Count of pairs of (a,b) where a^3+b^3=N: 2