search
Log In
0 votes
261 views

Given a non negative integer A,
following code tries to find all pair of integers (a, b) such that

  • a and b are positive integers
  • a <= b, and
  • a2 + b2 = A.
  • 0 <= A <= 100000

However, the code has a small bug. Correct the bug and submit the code.

vector<vector<int> > Solution::squareSum(int A) {
    vector<vector<int> > ans;
    for (int a = 0; a * a < A; a++) {
        for (int b = 0; b * b < A; b++) {
            if (a * a + b * b == A) {
                vector<int> newEntry;
                newEntry.push_back(a);
                newEntry.push_back(b);
                ans.push_back(newEntry);
            }
        }
    }
    return ans;
}

in Puzzles 261 views
0

as per logic, don't know about syntax of the programming language

  if (a * a + b * b == A) {

should be check before a ≤ b

  if ( (a ≤ b) && ( (a * a + b * b) ==  A ) ) {

 

and 

for (int b = 0; b * b < A; b++) {

should be as

for (int b = 0; b * b  A; b++) {

0
also i think there is no need to run the outer loop(i.e; loop for a) upto A. running it upto A/2 would be sufficient. because anyhow we don't want a to contribute more than A^2/2, as a should not be greater than b.
0

also i think there is no need to run the outer loop(i.e; loop for a) upto A. running it upto A/2 would be sufficient. because anyhow we don't want a to contribute more than A^2/2, as a should not be greater than b.

yes... but it is optimization of the code

0
Yeah it's optimisation. I just said it's a side note.:D

Please log in or register to answer this question.

Related questions

1 vote
1 answer
1
317 views
main() { int arr2D[3][3]; printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) ); }
asked May 15, 2016 in Puzzles Desert_Warrior 317 views
0 votes
1 answer
2
167 views
Input You are given a template in which you need to implement a function whose signature is given below. C int findWordInAGrid(char grid[128][128], int m, int n, char word[32]) /* return 0 for false, 1 for true. */ C++ bool findWordInAGrid(char grid[128][128], ... are: abc abedhi efgh Output: The output of the above example should be: abc: true abedhi: true efgh: false Constraints 1 ≤ m,n ≤ 100
asked Sep 6, 2017 in Puzzles Priyanka Sen 167 views
0 votes
2 answers
3
6 votes
3 answers
4
758 views
A bad king has a cellar of 1000 bottles of delightful and very expensive wine. A neighboring queen plots to kill the bad king and sends a servant to poison the wine. Fortunately (or say unfortunately) the bad king's guards catch the servant after he has only poisoned one bottle. ... is in mind of the king, how will he be able to do so ? (of course he has less then 1000 prisoners in his prisons)
asked Apr 9, 2016 in Puzzles pC 758 views
...