不定方程求解:
1.遇到较为简单的不定方程,直接暴力破解
//4x + 5y = 9
public static void main(String[] args){
for(int x = 0; x < 100; x++){
for(int y = 0; y < 100; y++){
if((x * 4 + y * 5) == 9){
System.out.println(x + "," + y);
}
}
}
}
2.当遇到较为复杂的不定方程,有多个解。
public class Main {
/**
* ax + by = c a = 4; b = 5 c = 13
* ax = c - by
* 1.先求出一个特殊解
* 2.求通解, x = x0 +bt; y = y0 + at
* @param args
*/
public static void main(String[] args){
int x0 = 0 , y0 = 0;
//求特解
for(int y = 0; y < 100; y++){
if(((13 - 5 * y) % 4) == 0){
System.out.println("y0 = "+ y + " ,x0 = "+((13 - 5 * y) / 4));
x0 = ((13 - 5 * y) / 4);
y0 = y;
break;
}
}
//求通解
for(int t = -100; t < 100; t++){
if((x0 + 5 * t) + (y0 + 4 * t) == 13)
System.out.println("y = "+ (x0 + 5 * t) + " ,x = "+(y0 + 4 * t));
}
}
}
3.水仙花数示例题:
求解:
import java.math.BigInteger;
/**
* @author 作者 : Cactus
* @version 创建时间:2018-2-25 下午06:16:13
*/
public class Main {
private static BigInteger[] base = new BigInteger[10];
public static void main(String[] args){
for(int i = 0; i < base.length; i++){
base[i] = calculate_21(i);
}
int[] a = new int[10]; // 记录每个数字取几次
f(a , 0 ,21);
}
private static BigInteger calculate_21(int n){
BigInteger a = BigInteger.ONE;
for(int i = 0; i < 21; i++){
a = a.multiply(BigInteger.valueOf(n));
}
return a;
}
private static void f(int[] a, int k, int sum){
if(sum == 0){
test(a);
return;
}
if(k == a.length - 1){
a[k] = sum;
test(a);
return;
}
for(int i = 0; i < sum; i++){
a[k] = i;
f(a , k + 1 , sum - i);
a[k] = 0;
}
}
private static void test(int[] a){
BigInteger bn = BigInteger.ZERO;
for(int i = 0; i < a.length; i++){
bn = bn.add(base[i].multiply(BigInteger.valueOf(a[i])));
}
String s = bn.toString();
if(s.length() != 21){
return;
}
int b[] = new int[10];
for(int i = 0; i < s.length(); i++){
b[s.charAt(i) - '0']++; // 字符转数字 s.charAt(i)-'0',‘9’-‘0’=9 ,‘1’-‘0’=1·······
}
for(int i = 0; i < 10; i++){
if(a[i] != b[i]){
return;
}
}
System.out.println(s);
}
}
运行结果如下: