Search code examples
javascriptnode.jsbrute-force

systematically solve algebra (brute force method)


I've searched around and tried myself, but couldn't quite figure out how to do it.

I have an equation, say a^2 + b^2 = c^2. I want to find what integers a, b, and c have to be to make this equation true using JavaScript (node.js). Obviously we know that it could be many things (such as a = 3, b = 4, and c = 5, but I'm only looking for the first answer the computer musters, no matter the answer. The only specification is that it must be an integer greater than 0, and solve it with brute force method, or just plugging in tons of numbers until it is true.

an example/one way I've thought of doing it is:

var
  a = 1;
  b = 1;
  c = 1;

if (Math.pow(a,2) + Math.pow(b,2) === Math.pow(c,2)) {
    console.log('you did it!');
} else {
    //something such as a++ or idk
  }

I don't know what to do for if the equation isn't true. My idea was first adding 1 to a, then subtracting 1 from a and adding 1 to b, and so on until the equation is true... sorta like this here

If you have any ideas on how to best do this, or if someone has solved this before and I couldn't find the source, please share!

Thanks


Solution

  • let a,b,c
    let high = 100
    let low = 1
    let checkedValues = []
    do {
        a = Math.round(Math.random() * (high - low) + low)
        b = Math.round(Math.random() * (high - low) + low)
        c = Math.round(Math.random() * (high - low) + low)
        if(checkedValues.find(arr => arr.every((v,i)=> v === [a,b,c][i]))) continue
        checkedValues.push([a,b,c])
    } while(Math.pow(a,2) + Math.pow(b,2) !== Math.pow(c,2))
    
    console.log('You found a = ', a, ' b = ', b, ' c = ', c)
    

    You are getting random values from low to high. You check did answer occured before. Then you put it in equation and check is it false, if yes, you are getting new random, else you have good answer.