search
HomeWeb Front-endJS TutorialJavaScript program to calculate number of spins divisible by 4

JavaScript 程序计算可被 4 整除的旋转次数

In this tutorial, we will learn to calculate the total number of spins for a given number that is divisible by 4.

Problem Statement - We are given a numerical value. We need to rotate the number clockwise or counterclockwise and count the total number of rotations that are divisible by 4.

Here we will learn two different ways to calculate the number of rotations divisible by 4.

Rotate the number and check if it is divisible by 4

In this method, we first convert the number into a string. We can perform n rotations on a string of length n. We will remove the first character of the string and add it to the last character of the string. Afterwards, we can check if the new number generated by the rotation is divisible by 4.

grammar

Users can follow the following syntax to check whether the rotation is divisible by 4 and rotate the numeric string.

for ( ) {
   if (parseInt(numStr) % 4 == 0) {
      count++;
   }
   numStr = numStr.substring(1, len) + numStr[0];
}

In the above syntax, the parseInt() method is used to convert the string into a number, and the substring() method is used to rotate the string.

algorithm

  • Step 1 - Use toString() method and convert the number to string.

  • Step 2 - Use a for loop to perform a total of "n" rotations on a string of length "n".

  • Step 3 - Convert the string to a number using parseInt() method and check if the number is divisible by 4. If the number is divisible by 4, the count variable is incremented and decremented by 1.

  • Step 4 - Use the substring() method to get the substring from the first index. Additionally, the first character of the string is appended to the end of the substring. This way, we can rotate the string and generate a new number.

Example 1

In the example below, we define the countRotations() function, which implements the above algorithm and returns the total number of rotations divisible by 4. In the output, the user can observe that the total number of spins of the number is divisible by 4.

<html>
<body>
   <h3 id="Program-to-find-the-total-number-of-rotations-divisible-by"> Program to find the total number of rotations divisible by 4 </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      // JavaScript program to find the total count of rotations divisible by 4
      let countRotations = (number) => {
         let numStr = number.toString();
         let len = numStr.length;
         let count = 0;
         
         // Loop to traverse the string
         for (let i = 0; i < len; i++) {
         
            // Check if the string is divisible by 4
            if (parseInt(numStr) % 4 == 0) {
               count++;
            }
            
            // Rotate the string
            numStr = numStr.substring(1, len) + numStr[0];
         }
         return count;
      }
      let number = 121342435345;
      output.innerHTML = "Total count of rotations divisible by 4 of " + number + " is " + countRotations(number);
   </script>
</body>
</html>

Check whether each pair of 2-digit numbers is divisible by 4

If the last 2 digits of any number are divisible by 4, we can say that number is divisible by 4. When rotating numbers, each pair of two digits appears at the end of the number. Therefore, we can check whether any pair of two numbers is divisible by 4; we can say that one rotation associated with that pair is divisible by 4.

grammar

Users can follow the syntax below to extract a pair of two-digit numbers from a number and check whether it is divisible by 4.

let lastDigit = num % 10;
num = Math.floor(num / 10);
let secondLastDigit = num % 10;
if ((secondLastDigit * 10 + lastDigit) % 4 == 0) {
   count++;
}

In the above syntax, we get the last and penultimate digit from the number. After that, we create a two-digit number using both and check if it is divisible by 4. If so, we increment the count variable.

algorithm

  • Step 1 - If the number is single digit, check if it is divisible by 4. Returns 1 if yes; otherwise returns 1. Otherwise return 0.

  • Step 2 - If the number contains two or more digits, initialize the "count" variable to 0.

  • Step 3 - Now, we need to create a pair using the last digit and the first digit of the number. Use the modulo operator to get the last digit and the Math.log() method to get the first digit.

  • Step 4 - Multiply the last digit by 10 and then multiply the first digit by 10. Then check if the result is divisible by 4. If it is divisible by 4, add 1 to the count.

  • Step 5 - Use a while loop to check the other two number pairs. In the while loop, use the modulo operator to get the last and second-to-last number. Create a pair using two numbers and check whether the pair is divisible by 2. If so, increase the count by 1.

Example 2

In this example, the countRotations() function counts the number of two-digit pairs that are divisible by 4. It implements the above algorithm and returns a count value after all operations are completed.

<html>
<body>
   <h3 id="Program-to-find-the-total-number-of-rotations-divisible-by"> Program to find the total number of rotations divisible by 4 </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      function countRotations(number) {
         //If the length of the number is equal to 1, check if the digit is a multiple of 4
         if (number < 10) {
            return number % 4 == 0 ? 1 : 0;
         } else {
            // Initialize count of rotations divisible by 4
            let count = 0;
            let num = number;
            //Check for the last digit and the first digit
            let lastDigit = number % 10;
            // Get the first digit from the number
            let firstDigit = Math.floor(number / Math.pow(10, Math.floor(Math.log10(number))));
            //If the last digit and first digit are divisible by 4, then add 1 to count
            if ((lastDigit * 10 + firstDigit) % 4 == 0) {
               count++;
            }
            while (num > 0) {
               // get last digit of number
               let lastDigit = num % 10;
               // get second last digit of number
               num = Math.floor(num / 10);
               let secondLastDigit = num % 10;
               if ((secondLastDigit * 10 + lastDigit) % 4 == 0) {
                  count++;
               }
            }
            return count;
         }
      }
      let number = 90645232432;
      output.innerHTML = "Total count of rotations divisible by 4 of " + number + " is " + countRotations(number);
   </script>
</body>
</html>

The user learned to find the total number of spins for a number divisible by 4. We see two different approaches. The first method converts the number to a string, rotates the string, converts the string to a number again, and checks whether the newly generated rotation is divisible by 4.

The second method counts the total number of two-digit pairs that are divisible by 4.

The above is the detailed content of JavaScript program to calculate number of spins divisible by 4. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.