java50题----04因式分解

本文介绍了一种使用Java实现的正整数分解质因数的方法,包括核心算法步骤和输入输出处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
将一个正整数分解质因数。
例如:输入90,打印出90=2*3*3*5.

*/
import java.util.*;
import java.io.*;

class Demo
{
	private Demo(){}

	private ArrayList arr = new ArrayList(0);

	private static Demo instance = new Demo();

	public static Demo getInstance()
	{
		return instance;
	}

	public void getSuShu(long integer)  ////2772 = 2*2*3*3*7*11
	{	
		long tmp = integer;

		printFunction(integer+"=");

		for(int i = 2; i <= tmp; )
		{
			if (i == tmp)
			{
				printFunction(i+"\n");
				arr.add(i);
				break;
			}
			else if(mod(tmp, i) == 0)
			{
				tmp = tmp/i;
				printFunction(i+"*");
				arr.add(i);
			}
			else
				i++;

		}

		//this.showArr(integer);

	}
	

	private long mod(long i, long div)
	{
		return i%div;

	}

	private void printFunction(Object obj)
	{
		System.out.print(obj.toString());
	}


	private void showArr(long integer)
	{
		
		for(int i = 0; i < arr.size(); i++)
		{
			printFunction("\n");
			printFunction(integer+"="+arr.get(i));
		}
	}
}



class MainClass 
{
	public static void main(String[] args) throws Exception
	{
		Demo d = Demo.getInstance();
		//d.getSuShu(8814);
		System.out.println("Please Input a natural number:");
		//录取键盘输入字节流对象
		InputStream in = System.in;
		
		//将字节流对象转换成字符流对象
		InputStreamReader reader = new InputStreamReader(in);
		
		//使用缓冲技术读取字符流对象
		BufferedReader buf = new BufferedReader(reader);

		String str = "";
		
		int i = 0;
		boolean flag = false;
		
		int index = 0;
		int ch = 0;
		int length = 0;
		String reg = "\\d+";
		while(true)
		{
			str = buf.readLine().trim();
			
			if(str.isEmpty())
				continue;
			
			if(str.equals("quit"))
			{
				System.exit(0);
			}
			
			if(str.matches(reg)== true)
			{
				i = Integer.parseInt(str, 10);
			
				d.getSuShu(i);
			}
			else
			{
				System.out.println("输入的数字不合法!!请重新输入:");

				continue;
			}
//			length = str.length();
//
//			for(index = 0; index <length; index++)
//			{
//				ch = str.charAt(index);
//				
//				if(ch < '0' || ch > '9')
//				{
//					System.out.println("Input Error!");
//					flag = false;
//					break;
//				}
//				else
//					flag = true;
//				
//			}
//			//将字符串转换成十进制整型
//			if(flag)
//			{
//				i = Integer.parseInt(str, 10);
//			
//				d.getSuShu(i);
//			}
		}
			
		
		
		
			
		

 
	}
}

/*

1.	ArrayList arr = new ArrayList(0);
	arr.add(E e); 可变长度数组增加元素
	arr.get(index);获取角标为index的元素
2.	将字符流输入对象转换成字符流输入对象
3.	Integer.parseInt(str, radix)将字符串转换成整数
4.	正则表达式的使用大大简化了代码。
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值