BigJobbies
BigJobbies

Reputation: 509

Is the number a sum of 2 cubes?

Im having a bit of bother with my script and im hoping someone could help out, i have a feeling im missing something simple, but another pair of eyes would be great.

Code as follows:

sumOfTwoCubes(91);

function sumOfTwoCubes($number) {
  var cube;
  var limit;
  var i, j, k;
  cube = $number;
  limit = Math.ceil(Math.exp(Math.log(cube) / 3));
  for (i = 1; i <= limit; i++) {
    for (j = 1; j <= limit; j++) {
      k = i * i * i + j * j * j;
      if (k == cube) {
        var out = "True";
      } else {
        var out = "False";
      }
    }
  }

  document.getElementById("result").innerHTML = out;
}
<p id="result"></p>

Upvotes: 0

Views: 370

Answers (2)

user5427813
user5427813

Reputation:

All you need to do is end your loop when you found the correct answer!

sumOfTwoCubes(91);
function sumOfTwoCubes($number)
{
  var cube;
  var limit;
  var i, j, k;
  var out = "False";
  cube = $number;
  limit = Math.ceil(Math.exp(Math.log(cube)/3));
    for(i = 1; i <= limit; i++){
      for(j = 1; j <= limit; j++){
        k = i * i * i + j * j * j;
        if(k == cube){
          var out = "True";
          break;
        }
      }
      if (out == "True")
        break;
    }

  document.getElementById("result").innerHTML = out;
}

Now it does show "True"! All I done is:
- Added a break when the k == cube, so it will leave the inner for.
- Added an if (out == "True") break;, so if the out is "True", it will end your loop and you will see a "True" message inside result element!

Upvotes: 0

Jalil
Jalil

Reputation: 450

You can do it like this.

function sumOfTwoCubes($number)
{
  var cube;
  var limit;
  var i, j, k;
  cube = $number;
  limit = Math.ceil(Math.exp(Math.log(cube)/3));
  for(i = 1; i <= limit; i++){
    for(j = 1; j <= limit; j++){
      k = i * i * i + j * j * j;
      if(k == cube){
        return document.getElementById("result").innerHTML = "TRUE";
      }
    }
  }
  return document.getElementById("result").innerHTML = "False";
}

sumOfTwoCubes(91);
<p id="result"></p>

Upvotes: 2

Related Questions