不定方程求解

不定方程求解:

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);
    }
}

运行结果如下:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜鹊先生Richard

随缘~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值