How to calculate complex roots?

let a = Number(prompt("Enter the value of a"));
let b = Number(prompt("Enter the value of b"));
let c = Number(prompt("Enter the value of c"));
let x, y;
if (b * b - 4 * a * c == 0) {
  x = -b / (2 * a);
  console.log(x);
}
else if (b * b - 4 * a * c > 0) {
  x = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  y = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  console.log(x);
  console.log(y);
}
else {
  x = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  y = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  console.log(x);
  console.log(y);
}

I am getting NaN. I can’t eat it as I don’t have the chutney rn lol. jk.
I know this is wrong, but can you give me a no-code answer to solve this problem? I want to write code myself, I want hints. I don’t want to look into google or chatgpt as they’ll solve this problem 1000 times already in google it’s available.

Clues…
What does b * b - 4 * a * c give you?
Now read this…

EDIT: It took me long enough but I just got your joke, must be a cultural thing :stuck_out_tongue_winking_eye:

3 Likes

I understand that Math.sqrt(-value) returns NaN. I don’t understand how we can calculate the complex roots.

Ah, ok, complex roots is a thing :stuck_out_tongue_winking_eye:
Im not the one for this, me dumb, i didnt even finish year 10.
If it was me Id just use Math.js or is it complex.js

let a = Number(prompt("Enter the value of a"));
let b = Number(prompt("Enter the value of b"));
let c = Number(prompt("Enter the value of c"));
let realPart, imaginaryPart;
let x, y;
if (b * b - 4 * a * c == 0) {
  x = -b / (2 * a);
  console.log(x);
}
else if (b * b - 4 * a * c > 0) {
  x = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  y = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  console.log(x);
  console.log(y);
}
else {
  realPart = -b / (2 * a);
  imaginaryPart = Math.sqrt(4 * a * c - b * b) / (2 * a);
  console.log(
    "Complex roots:",
    realPart + " + " + imaginaryPart + "i",
    realPart + " - " + imaginaryPart + "i"
  );
}

Problem is solved.