0
点赞
收藏
分享

微信扫一扫

【递归分治】半数集问题java

westfallon 2022-03-30 阅读 73
java

半数集问题

给定一个自然数n,由n开始可以依次产生半数集set(n)中的数如下:

(1) n ∈set(n);

(2) 在n的左边加上一个自然数,但该自然数不能超过最近添加的数的一半;

(3) 按此规则进行处理,直到不能再添加自然数为止。

以6为例子,6,6前面可以加1,2,3生成16,26,36,26前面可以加1生成126,同理36生成136.所以6的半数集元素个数为6分别是6,16,26,36,126,136

以12为例子,只加一个数字产生的元素有612,512,412,312,212,112。因为之后加的数字与‘12’没有关系,只与第一次加的数字有关,612,512,412,312,212,112产生的半数集元素的个数相当于6,5,4,3,2,1的半数集的个数,不难得到如下公式。

请添加图片描述

参考

import java.io.*;
import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        File f1 = new File("src//set.txt");
        File f2 = new File("src//2.txt");
        FileReader fr = null;
        BufferedReader br = null;
        FileWriter fw = null;
        BufferedWriter bw = null;
        int i, n;
        String s;
        try {
            fr = new FileReader(f1);
            br = new BufferedReader(fr);
            fw = new FileWriter(f2);//创建文件写入对象
            bw = new BufferedWriter(fw);//创建字符流写入对象
        } catch (Exception e) {
            System.out.println("文件打开失败");
        }
        try {
            while ((s = br.readLine()) != null) {
                n = Integer.parseInt(s);
                bw.write(setn(n,n)+"");
                bw.newLine();
            }
            bw.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }





//        int n;
//        Scanner scan = new Scanner(System.in);
//        n=scan.nextInt();
//        System.out.println(setn(n,n)+1);//74

    }

    public static int setn(int n, int pre) //不包含其本身
    {
        int count = 0, i, m, z;
        if (pre < 2)
            return 0;
        for (i = 1; i <= pre / 2; i++) {
            count++;//该数属于半数集
            z = i * (int) Math.pow(10, wei(n)) + n;//找改数的子半数集
            count += setn(z, i);
        }
        return count;
    }

    public static int wei(int n) {
        if (n <= 0)
            return -1;
        int i = 0;
        while (n != 0) {
            n /= 10;
            i++;
        }
        return i;
    }

}

举报

相关推荐

0 条评论