The Gateway to Computer Science Excellence
0 votes
93 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 by (5 points) | 93 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.

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,645 questions
56,601 answers
195,853 comments
102,227 users