// 先上结论:将绳子等分会使得结果最大。
// 并且等分的长度为3时,结果乘积最大。
class Solution {
public:
int cuttingRope(int n) {
if(n==2) return 1;
if(n==3) return 2;
if(n==4) return 4;
long long res = 1;
while(n > 4){
n = n-3;
res = res * 3 % 1000000007;
}
res = res * n % 1000000007;
return res;
}
};
class Solution {
public int cuttingRope(int n) {
if (n <= 3) {
return n - 1;
}
int a = n / 3;
int b = n % 3;
int c = 1000000007;
if (b == 0) {
return (int) pow(3, a);
} else if (b == 1) {
return (int) (pow(3, a - 1) * 4 % c);
} else {
return (int) (pow(3, a) * 2 % c);
}
}
long pow(int a, int b) {
long res = 1;
int c = 1000000007;
for (int i = 1; i <= b; i++) {
res = (res * a) % c;
}
return res;
}
}
class Solution {
public int cuttingRope(int n) {
if (n==2) {
return 1;
}
if (n==3) {
return 2;
}
int res = n / 3;
int mod = n % 3;
int p = 1000000007;
if (mod == 0) {
return (int)pow(3, res);
} else if (mod == 1) {
return (int)(pow(3,res - 1) * 4 % p);
} else {
return (int)(pow(3, res) * 2 % p);
}
}
//快速幂求余
public long pow(int a, int n) {
long sum = 1;
long temp = a;
int p = 1000000007;
while (n > 0) {
// 最低位为1,底数乘上去
if ((n&1) == 1){
sum = (sum * temp) % p;
}
temp = (temp * temp) % p;
n = n >> 1;
}
return sum;
}
}
class Solution {
public int cuttingRope(int n) {
if(n<=3){
return n-1;
}
if(n<=4){
return 4;
}
long res = 1;
while (n > 4) {
n -= 3;
res = res * 3 % 1000000007;
}
res = res * n % 1000000007;
return (int) res;
}
}
class Solution {
public:
int cuttingRope(int n) {
if (n <= 3) {
return n - 1;
}
const long p = 1000000007;
int a = n / 3;
int b = n % 3;
if (b == 0) {
return int(power(3, a, p));
} else if (b == 1) {
return int(power(3, a - 1, p) * 4 % p);
} else {
return int(power(3, a, p) * 2 % p);
}
}
long power(unsigned long base, int n, long p) {
long result = 1;
while (n > 0) {
if (n & 1) {
result = result * base % p;
}
base = base * base % p;
n >>= 1;
}
return result;
}
};
共以下 8 个回答
加了个大数的取模运算
简单的快速幂求余,题解里有另外一种没看懂。。
循环取余
DP实现会溢出,采用循环取余法
时空复杂度O(1)