Last active
January 18, 2021 09:09
-
-
Save chengfeng-1992/1ab94bfdab77d395a0dd87b6feb51974 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.util.Random; | |
public class Test { | |
public static void main(String[] args) throws Exception { | |
int x = 100; | |
int y = 10; | |
int a = 5; | |
int b = 15; | |
decompose(x, y, a, b); | |
} | |
private static void decompose(int x, int y, int a, int b) throws Exception { | |
if (!((x >= a * y) && (x <= b * y))) { | |
throw new Exception("该题无解!"); | |
} | |
int remainder = x - a * y; | |
final int max = b - a; | |
// System.out.println("个数=" + y); | |
// System.out.println("余数=" + remainder); | |
// System.out.println("最大值=" + max); | |
// | |
Random random = new Random(); | |
for (int i = 0; i < y - 1; i++) { | |
int amount = 0; | |
do { | |
amount = random.nextInt(max + 1); | |
} while (remainder - amount < 0 || remainder - amount > max * (y - i - 1)); // 保证后面的在区间内 | |
remainder -= amount; | |
System.out.println(amount + a); | |
} | |
// 最后一个值 | |
System.out.println(remainder + a); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment