Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
JavaScript how to ensure sum of two numbers is not negative

I am creating a math game for kids using JavaScript and created a function that will generate two numbers, first number is positive and second is negative so that students will have to sum the given two number, but i want to generate numbers that the sum will not be a negative number.

my current functions

function randomIntFromInterval(min, max) { // min and max included 
    return Math.floor(Math.random() * (max - min + 1) + min)
}

function generateRandomSubtractNumber() {
    var base_number = randomIntFromInterval(2, 10)
    var sub_number = -randomIntFromInterval(1, 5);
    console.log(base_number, sub_number)
    return  {
        "base_number" : base_number,
        "sub_number" : sub_number,
        "total" : base_number +  sub_number 
    }
}

I tried to put an if statement to check if the object.total will be less than zero but not sure how to re-generate again if the statement is true.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I think you can pass base_number as param to randomIntFromInterval.

 var base_number = randomIntFromInterval(2, 10)
 var sub_number = -randomIntFromInterval(1, base_number);
about 4 years ago · Juan Pablo Isaza Report

0

function generateRandomSubtractNumber() {
    var base_number = randomIntFromInterval(2, 10)
    var sub_number = randomIntFromInterval(1, 5);
    return   base_number >= sub_number?

    {
        "base_number" : base_number,
        "sub_number" : -sub_number,
        "total" : base_number - sub_number 
    }:
   
   {
        "base_number" : sub_number,
        "sub_number" : -base_number ,
        "total" : sub_number - base_number 
    }
}
about 4 years ago · Juan Pablo Isaza Report

0

I see 2 solutions for this :

  • The first one is to do a while loop which regenerate these numbers while the sum is negative
  • The second one (better) is to generate the second between 1 and the first number, this way the first one (positive) is always greater than the second one (negative)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!