Outputting the square root of integers ranging from 4 to 9999

I'm looking to calculate the square root of all numbers up to 9999. Are there any ways to instruct the program to skip numbers that do not have a perfect square root? Below is the current code I am using:

let i=1;

for (i===1;i>=1 && i <10000;i++){
    let b = Math.sqrt(i);
    console.log(`${i} = ${b}`);
}

Answer №1

To determine if the integer value matches the original value, you need to compare them.

let i=1;

for (i=1;i>=1 && i <10000;i++){
    let b = Math.sqrt(i);
    if (Math.trunc(b) == b)
        console.log(`${i} = ${b}`);
}

Instead of using Math.trunc(b), consider using one of these alternatives:

  • Math.round(b)
  • Math.floor(b)
  • Math.ceil(b)
  • parseInt(b, 10)

Answer №2

Instead of testing every number up to 10000, you can calculate powers of two directly:

let count = 0, i = 0;
while (count < 10000) {
  i++;
  let b = i * i;
  console.log(`${i} = ${b}`);
  count = b;
}

Another way to approach this, as suggested in the comments, is to use a more elegant for-loop:

for (let i = 1; i*i < 10000; i++) {
  console.log(`${i*i} = ${i}`);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript to define a method that returns a value within a .then() function

Currently in the process of coding a function to add a user to a database, with the requirement of returning a promise with the specified User class that I have created: async createUser(user: User): Promise<User> { const userObject: User = user; ha ...

How to generate PDF downloads with PHP using FPDF

I am attempting to create a PDF using FPDF in PHP. Here is my AJAX call: form = $('#caw_auto_form'); validator = form.validate(); data = form.serializeObject(); valid = validator.form(); //alert("here"); ajax('pos/pos_api.php',data,fun ...

Preserve the specific date and time in the designated timezone

Utilizing the react-datePicker library requires using new Date() as input. I need to save the user's selected date, time, and timezone in such a way that regardless of their location, they will see Feb 10 2024 02:00 BST in the Date Object. Currently, ...

retrieve all users who are not currently in the group

I'm currently struggling to retrieve all users who are not members of a particular group within a many-to-many association. After investing several hours into researching and experimenting, I've developed the following code. However, it falls sh ...

Verify that the user visits the URL in next.js

I need to ensure that a function only runs the first time a user visits a page, but not on subsequent visits. For example: When a user first opens the HOME page, a specific condition must be met. When they then visit the /about page, the condition for th ...

How can I locally store 3D models and textures using three.js?

Currently working on a game using three.js, where each game level is on a different page. However, when transitioning from one level to another, the browser reloads the page which can be quite slow. Is there a way to store 3D models locally so they don&apo ...

The element is implicitly assigned to an 'any' type due to the inability to use a 'string' type expression to index the 'Breakpoints' type

I have a question related to TypeScript that I need help with. My objective is to create a custom hook for handling media queries more efficiently. Instead of using useMediaQuery(theme.breakpoints.down('md');, I want to simplify it to: useBreakP ...

"Utilizing Trackball controls, camera, and directional Light features in ThreeJS version r69

I am struggling to synchronize trackball controls and camera with the directional light. Here is my situation: I start by initializing an empty scene with a camera, lights, and controls. Then, I load a bufferGeometry obj, calculate its centroid, and adjus ...

Having difficulties retrieving the <td> id using jQuery

I am a beginner in the world of JavaScript and jQuery, and I am currently attempting to extract both the ID and the value of an element. Here is my initial AJAX request: $.ajax({ type: "POST", url: "Home/AddText", data: JSON.stringify({ te ...

Where is the first next() call's argument located?

I'm facing an issue with a simple generator function function *generate(arg) { console.log(arg) for(let i = 0; i < 3;i++) { console.log(yield i); } } After initializing the generator, I attempted to print values in the console: var gen ...

One way to clear out a directory in Node.js is to delete all files within the directory while keeping

Can anyone guide me on how to delete all files from a specific directory in Node.js without deleting the actual directory itself? I need to get rid of temporary files, but I'm still learning about filesystems. I came across this method that deletes ...

Sending a JSON object as a parameter in JavaScript with whitespace within the data

It appears that the code is functional when there are no spaces in the content <a onclick=fbShareDialog("{\"name\":\"aaaaaaa\"}"> However, if there is a space present <a onclick=fbShareDialog("{\"name\":\"bbbb ...

Using Ajax to poll a Celery task

I am working on a Celery task that updates a PostgreSQL database gradually. In my Django application, I want to fetch the latest data from the database and display it in a template in real-time as the task progresses. I am looking to implement this real-ti ...

Creating dynamic values in data-tables using Vuetify

As I work with JSON data, my current task involves formatting it using Vuetify's Data Tables. The official documentation provides guidance on defining table headers as shown below: import data from './data.json' export default { data ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

Tips for adjusting the color of boxes within a grid

I've built a grid containing multiple boxes, each identified with an id of box + i. However, I'm encountering difficulties when attempting to implement an on-click function to change the color of each box. Below is the code snippet in question: f ...

I'm looking for a method to trigger onChange() specifically on Internet Explorer using only JavaScript, HTML, and CSS without relying on jQuery

Looking for a way to utilize onChange() only on Internet Explorer using Javascript, HTML, CSS (No Jquery). My current code successfully sends the input to my function upon onChange(), but it seems to work smoothly on Chrome and not on IE. Is there a meth ...

When the table is clicked, a dynamic accordion table should appear

My current code displays a table inside another table using a PHP for loop. While I can retrieve the data successfully, I'm facing issues with the UI layout and accordion functionality. The inner table is displaying beside the outer table instead of b ...

Tips for hiding a div element until its visibility is toggled:- Set the display property of

Looking for some guidance on this jQuery code I'm working with to create a toggle menu. The goal is to have the menu hidden when the page loads, and then revealed when a button is clicked. However, currently the menu starts off being visible instead o ...