Sword Finger Offer 14- II. Cut the Rope II (C++) Greedy + Fast Power

Here is a rope with a length of n. Please cut the rope into m segments of integer length (m and n are integers, n>1 and m>1). The length of each rope is k[0],k [1]...k[m-1]. What is the maximum possible product of k[0] k[1] …*k[m-1]? For example, when the length of the rope is 8, we cut it into three pieces with lengths of 2, 3, and 3. The maximum product obtained at this time is 18.

The answer needs to be modulo 1e9+7 (1000000007). If the initial result of the calculation is: 1000000008, please return 1.
Find the remainder more than Offer 14- I

Example 1:

输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1

Example 2:

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36

prompt:

2 <= n <= 1000
Note: This question is the same as the main site question 343: https://leetcode-cn.com/problems/integer-break/

class Solution {
    
    
public:
    int cuttingRope(int n) {
    
    
		if (n <= 3) return n - 1;
        int b = n % 3, p = 1000000007;
        long rem = 1, x = 3;
		
		//下面为快速幂方法,其中多了求余数部分, 
		//  n / 3 - 1是为了留出来一个“3”,
        for (int a = n / 3 - 1; a > 0; a /=2 ) {
    
    
            if ((a & 1) == 1) {
    
    
                rem = (rem * x) % p;
            }
            x = (x * x) % p;
        }

        if (b == 0) return (int) (rem * 3 % p);//3就是快速幂留出来的3
        if (b == 1) return (int) (rem * 4 % p);//4就是3+1,因为相乘所以4等于2*2
        return (int) (rem * 6 % p);6就是3+2那一段绳子,因为相乘所以6等于3*2
    }
};

Insert picture description here

The remainder of large numbers:

Insert picture description here

Author: jyd
link: https: //leetcode-cn.com/problems/jian-sheng-zi-ii-lcof/solution/mian-shi-ti-14-ii-jian-sheng-zi-iitan-xin-er -fen-f/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114736618
Recommended