java 质因数分解

2021/5/23 20:25:30

本文主要是介绍java 质因数分解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

import java.util.TreeSet;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.stream.Collectors;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.LineNumberReader;
import java.io.FileWriter;
import java.io.BufferedWriter;

/**
 * @Author:Administrator
 * @Date:2021-05-23
 */
public class Factorization {

    /** 质数海*/
    public static TreeSet<Long> primePoor = new TreeSet();
	/** 最小质数*/
	private static final long MIN_FAC = 2L;
	/** 质数缓存*/
	private static String filename = "prime.txt";
	/** 文件路径*/
	private static String filepath;
	/** 分隔符*/
	private static String delimiter = ",";
	/** 每行数字*/
	private static Integer cols = 10;
	

    static {
		//初始化池, 100以内的质数
		Long[] prime25 = {2L,3L,5L,7L,11L,13L,17L,19L,23L,29L,31L,37L,41L,43L,47L,53L,59L,61L,67L,71L,73L,79L,83L,89L,97L};
		filepath = Factorization.class.getResource("/").getPath();
		// System.out.println("\n类路径:"+path);
		File file = new File(filepath, filename);
		List<Long> prime = new ArrayList(Arrays.asList(prime25));
		// for(int i=0; i<prime25.length; i++){
			// prime.add(prime25[i]);
		// }
		if(file.exists()){
			String str = FileUtil.read(file.getPath());
			if(str != null && !"".equals(str)){
				String[] strArr = str.split(delimiter);
				prime = (List<Long>)new ArrayList(Arrays.asList(strArr)).stream().map(it -> Long.parseLong((String)it)).collect(Collectors.toList());
			}
		}
		// prime.forEach(System.out::println);
		for(int i=0;i<prime.size();i++){
			primePoor.add(prime.get(i));
		}
    }
    public static void main(String[] args){
        Scanner sc = null;
        try {
            sc = new Scanner(System.in);
            long a = 2L;
            while(a>1){
                System.out.println("\n请输入待分解的自然数:");
                a = sc.nextLong();
                System.out.println(fact(a));
            }
			int size = primePoor.size();
			System.out.println("退出...\n");
			StringBuilder sb = new StringBuilder();
			for(int i=0;i<size;i++){
				sb.append(primePoor.pollFirst());
				if(i<size-1){
					sb.append(delimiter);
				}
				if((i+1) % cols==0){
					sb.append("\r\n");
				}
				
			}
			// File file = new File(filepath, filename);
			FileUtil.write(sb.toString(), filepath + filename);
        }
        catch (Exception e) {
            // System.out.println("error");
            e.printStackTrace();
        }
        finally {
            if(sc!=null) {
                try {
                    sc.close();
                }
                catch (Exception ec) {
                    System.out.println("close scanner error");
                }
            }
        }
    }

    /**
     *
     */
    public static String fact(long a){
        List<Long> arr = factArr(a);
        return arr.stream().map( it -> it + "").collect(Collectors.joining("*"));
    }
	
	/**
	 * 分解结果
	 */
	public static List<Long> factArr(long a){
		List<Long> res = new ArrayList();
		if( a <= MIN_FAC){
			res.add(a);
			return res;
		}
		long begin = MIN_FAC;
        while(!isPrime(a)){
            if(a%begin==0){
                a /= begin;
                res.add(begin);
            }
            else{
                begin = nextPrime(begin);
            }
        }
		res.add(a);
		return res;
	}

    /**
     * 下一个质数
     */
    public static long nextPrime(long a){
        if(a<MIN_FAC)
            return MIN_FAC;
		++a;
        Long res = (Long)primePoor.ceiling(a);
        if(res != null)
            return res;
        while(true){
			res = a;
            if(isPrime(res)){
				return res;
			}
			a++;
        }
    }

    /**
     * 判断是否是质数
     */
    public static boolean isPrime(long a){
        if (a<MIN_FAC)
            return false;
        if(primePoor.contains(a))
            return true;
        long i=2L;
        double limit = Math.ceil(Math.sqrt(a));
		for(Iterator iter = primePoor.iterator(); iter.hasNext(); ) {
			i = (Long)iter.next();
			if(a%i==0){
				return false;
			}
		}
		i++;
        while (i<=limit) {
            if(a%i==0){
				return false;
			}
			if(i<1000000 && isPrime(i)){
				primePoor.add(i);
			}
			i++;
        }
		primePoor.add(a);
        return true;
    }

    /**
     * 绝对值
     */
    public static long abs(long a){
        long i = a >> 3;
        return ((a^i)-i);
    }
}
class FileUtil {
	
	/**
     * 读取文本内容
     */
    public static String read(String filepath){
        File file = new File(filepath);
        if (!file.exists()){
			try {
				file.createNewFile();
			} catch (Exception e){
				e.printStackTrace();
			}
            
            return "";
        }
        StringBuilder content = new StringBuilder();
		String s;
        BufferedReader br = null;
		try {
			
			br = new BufferedReader(new FileReader(file));
			while ((s =br.readLine()) != null) {//逐行读取文件内容,不读取换行符和末尾的空格
				content.append(s);
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(br != null){
				try {
					br.close();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		}
        return content.toString();
    }
	
	/**
     * 读取文件指定行数(读取多行)
     * @param filePath
     * @param max 读取行数
     * @param page 第几个 max
     */
    public static String read(String filePath,int max, int page){
        FileReader fr = null;
        page = page > 0 ? page : 1;
        max = max > 0 ? max : 30;
        LineNumberReader reader = null;
        StringBuilder res = new StringBuilder();
        try {
            fr = new FileReader(filePath);
            reader = new LineNumberReader(fr);
            int i = 0, b = (page-1) * max, e = page * max;
            String s = null;
            while((s = reader.readLine()) != null){
                if(b <= i++ && i< e){
                    res.append(s);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResource(fr, reader);
        }
        return res.toString();
    }

	/** 写*/
    public static boolean write(String content, String filepath){
        File file =new File(filepath);
        if(!file.exists()){
            try {
				file.createNewFile();
			} catch (Exception e){
				e.printStackTrace();
			}
        }
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file));
            bw.write(content);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null){
                try {
                    bw.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 关闭资源
     * @param fr
     * @param reader
     */
    static void closeResource(FileReader fr,LineNumberReader reader){
        try {
            if(reader != null){
                reader.close();
            }
            if(fr != null){
                fr.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


这篇关于java 质因数分解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程