Table of Contents
usage instructions
Simple method: right-rotate numbers
algorithm
Example
Output
Efficient method: multiply by X
in conclusion
Home Backend Development C++ Minimum cost of converting 1 to N, which can be achieved by multiplying by X or right rotation of the number

Minimum cost of converting 1 to N, which can be achieved by multiplying by X or right rotation of the number

Sep 12, 2023 pm 08:09 PM
rotate cost Convert

Minimum cost of converting 1 to N, which can be achieved by multiplying by X or right rotation of the number

We can use the following technique to find the cheapest way to multiply X or right-rotate its number from 1 to N. To monitor the initial minimum cost, create a cost variable. When going from N to 1, check whether N is divisible by X at each stage. If it is, then divide N by X to update it and continue the process. If N is not divisible by X, then loop the digits of N to the right to increase its value. Add the cost variable in this case. The final cost variable value will be the minimum amount required to turn 1 into N. The algorithm efficiently determines the minimum operations required to perform the desired transformation using numeric rotation or multiplication.

usage instructions

  • Naive Approach: Right rotation of numbers

  • Efficient method: multiply by X

Simple method: right-rotate numbers

The naive approach is to start with the number 1 and repeatedly rotate its numbers to the right until you reach the target number N. On each spin, the last number changes to the first number. Although conceptually simple, this strategy can be inefficient for large values ​​of N and may require many steps to reach the target number. As N increases, the number of rotations also increases rapidly, making it a less effective method of determining the minimum cost of converting 1 to N. Due to its inefficiency, this method is not recommended for large values ​​of N, while other methods, such as dividing N by X, have proven to be more efficient in finding the lowest cost of the transformation.

algorithm

  • Create the variable "cost" to track the steps required to reach N and initialize it to 1 to represent the current value.

  • Repeat these instructions until the current number equals N:

    Rotate the digits of the current number to the right so that the last digit becomes the first digit.

    Record the number of required rotations by incrementing the "cost" variable by 1.

  • Once the current number equals N, the "cost" variable stores the minimum number of steps required to rotate the original integer (1) to N using a right rotation.

Example

#include <iostream>
#include <cmath>

int rotateDigits(int num, int numDigits) {
    return (num / 10) + (num % 10) * std::pow(10, numDigits - 1);
}

int main() {
    int N = 123; // Replace this with your desired N value

    int current = 1;
    int cost = 0;
    bool found = false;

    while (current != N) {
        int numDigits = std::to_string(current).length();
        current = rotateDigits(current, numDigits);
        cost++;

        if (cost > N) {
            std::cout << "N cannot be reached from 1 using right rotations." << std::endl;
            found = true;
            break;
        }
    }

    if (!found) {
        std::cout << "Minimum steps to reach N: " << cost << std::endl;
    }
    return 0;
}
Copy after login

Output

N cannot be reached from 1 using right rotations.
Copy after login

Efficient method: multiply by X

The best way to minimize the cost of multiplying 1 by N is to periodically divide N by X until the result is 1. To achieve this, initialize a cost variable to monitor the minimum cost. We determine whether N is divisible by X by starting with the value of N. If both N and X are divisible, the cost increases and a division operation is performed. Repeat this process until N equals 1. This method is more efficient than "number right rotation" because it requires fewer steps to get the result 1. Due to its faster and more efficient nature, it is the preferred method for determining the lowest switching cost.

algorithm

  • To track minimum cost, initialize the variable "cost" to 0.

  • Start from a given target number N, using a fixed multiplier X.

  • As long as N is greater than 1, repeat steps 4 to 6.

  • Assuming N% X == 0, determine whether N is divisible by X.

  • If N is divisible (N = N / X), divide N by X and add 1 to the "cost" variable.

  • If not divisible, loop the N numbers to the right (by moving the last digit to the first) and increase the "cost" by 1.

  • Repeat steps 3 to 6 until N becomes 1.

  • The last "cost" represents the minimum required to multiply by X or shift the number right to change 1 to N.

Example

#include <iostream>
#include <cmath>

int main() {
    int X = 3;
    int N = 100;
    int cost = 0;

    while (N > 1) {
        if (N % X == 0) {
            N /= X;
            cost++;
        } else {
            int lastDigit = N % 10;
            N = (N / 10) + (lastDigit * std::pow(10, std::floor(std::log10(N))));
            cost++;
        }
    }

    std::cout << "Final cost: " << cost << std::endl;

    return 0;
}
Copy after login

Output

Final cost: 2
Copy after login

in conclusion

In summary, when it comes to determining the lowest cost of converting 1 to N by multiplying by X or right-rotating the number, the efficient method of multiplying by The more streamlined approach provided by efficient methods requires fewer steps to reach the required number of N. On the other hand, naive methods can be ineffective and time-consuming, especially for higher values ​​of N. We can reduce the required processes and use efficient methods to determine the most economical way to convert 1 to N. This strategy solves the problem of determining the minimum cost of this conversion process and proves to be a more useful and efficient algorithm.

The above is the detailed content of Minimum cost of converting 1 to N, which can be achieved by multiplying by X or right rotation of the number. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A simple guide to converting USDT ERC20 to TRC20 A simple guide to converting USDT ERC20 to TRC20 Jan 18, 2024 pm 06:09 PM

We teach you step by step how to convert USDTERC20 to TRC20 network. This is because many people like to move the USDT stablecoin from the Ethereum network to the Tron network to save on transaction fees. So, if you want to convert your ERC-20 tokens to TRC-20, I believe this tutorial will be helpful to you. The difference between ERC-20 and TRC-20 ERC-20 tokens and TRC-20 tokens represent tokens based on the Ethereum network and the Tron network respectively. There are some differences between the two networks, mainly in the following aspects: First, the Ethereum network often faces congestion and high gas fees, which may lead to transaction delays and high transaction costs. In comparison, the Tron network is relatively less congested

Practical tips for converting full-width English letters into half-width form Practical tips for converting full-width English letters into half-width form Mar 26, 2024 am 09:54 AM

Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

How to convert ODT to Word in Windows 11/10? How to convert ODT to Word in Windows 11/10? Feb 20, 2024 pm 12:21 PM

In this article, we will show you how to convert OpenDocumentTextDocument (ODT) files to Microsoft Word (Docx, DOC, etc.). Format. How to Convert ODT to Word in Windows 11/10 Here is how you can convert ODT documents to DOC or DOCX format on Windows PC: Convert ODT to Word using WordPad or Word The first method we are going to show you Is to use WordPad or MicrosoftWord to convert ODT to Word. Here are the steps to achieve this: First, open the WordPad app using the Start menu. Now, go to

How to convert AI files to CDR format How to convert AI files to CDR format Feb 19, 2024 pm 04:09 PM

AI files refer to vector graphics files created by Adobe Illustrator (AI for short) software, while CDR files refer to vector graphics files created by CorelDRAW software. Since these two softwares are developed by different manufacturers, their file formats are different and cannot be directly converted to each other. However, we can convert AI files to CDR files through some methods. A commonly used conversion method will be introduced below. Step 1: Export AI files to EPS format AdobeIllust

How to convert a virtual machine to a physical machine? How to convert a virtual machine to a physical machine? Feb 19, 2024 am 11:40 AM

Converting a virtual machine (VM) to a physical machine is the process of migrating a virtual instance and associated application software to a physical hardware platform. This conversion helps optimize operating system performance and hardware resource utilization. This article aims to provide an in-depth look at how to make this conversion. How to implement migration from virtual machine to physical machine? Typically, the conversion process between a virtual machine and a physical machine is performed outside the virtual machine by third-party software. This process consists of multiple stages involving the configuration of virtual machines and the transfer of resources. Prepare the physical machine: The first step is to ensure that the physical machine meets the hardware requirements for Windows. We need to back up the data on a physical machine as the conversion process will overwrite the existing data. *Username and password for an administrator account with administrator rights to create system images. will be virtual

Golang time processing: How to convert timestamp to string in Golang Golang time processing: How to convert timestamp to string in Golang Feb 24, 2024 pm 10:42 PM

Golang time conversion: How to convert timestamp to string In Golang, time operation is one of the very common operations. Sometimes we need to convert the timestamp into a string for easy display or storage. This article will introduce how to use Golang to convert timestamps to strings and provide specific code examples. 1. Conversion of timestamps and strings In Golang, timestamps are usually expressed in the form of integer numbers, which represent the number of seconds from January 1, 1970 to the current time. The string is

Detailed explanation of the implementation method of converting PHP months to English months Detailed explanation of the implementation method of converting PHP months to English months Mar 21, 2024 pm 06:45 PM

This article will introduce in detail how to convert months in PHP to English months, and give specific code examples. In PHP development, sometimes we need to convert digital months to English months, which is very practical in some date processing or data display scenarios. The implementation principles, specific code examples and precautions will be explained in detail below. 1. Implementation principle In PHP, you can convert digital months into English months by using the DateTime class and format method. Date

How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone Mar 21, 2024 pm 01:21 PM

QQ Music allows everyone to enjoy watching movies and relieve boredom. You can use this software every day to easily satisfy your needs. A large number of high-quality songs are available for everyone to listen to. You can also download and save them. The next time you listen to them, you don’t need an Internet connection. The songs downloaded here are not in MP3 format and cannot be used on other platforms. After the membership songs expire, there is no way to listen to them again. Therefore, many friends want to convert the songs into MP3 format. Here, the editor explains You provide methods so that everyone can use them! 1. Open QQ Music on your computer, click the [Main Menu] button in the upper right corner, click [Audio Transcoding], select the [Add Song] option, and add the songs that need to be converted; 2. After adding the songs, click to select Convert to [mp3]

See all articles