JAVA分解质因子

/*题目

分解质因数(5分)

题目内容:

每个非素数(合数)都可以写成几个素数(也可称为质数)相乘的形式,这几个素数就都叫做这个合数的质因数。比如,6可以被分解为2x3,而24可以被分解为2x2x2x3。

现在,你的程序要读入一个[2,100000]范围内的整数,然后输出它的质因数分解式;当读到的就是素数时,输出它本身。

输入格式:

一个整数,范围在[2,100000]内。

输出格式:

形如:

n=axbxcxd

n=n

所有的符号之间都没有空格,x是小写字母x。

输入样例:

18

输出样例:

18=2x3x3


*/




import java.util.Scanner; public class Main { public static boolean IsPrime(int a) { boolean t=true; for (int i =2;i<a;i++) { if(a%i==0) { t=false;//就不是素数了 break; } } return t; } public static String myMethod(int a) { String Str=""; int count=1; if(IsPrime(a))//如果输入的数字a是素数,就直接输出结果 { Str=a+"="+a; } else//否则,继续 { while(!IsPrime(a))//如果当前a的值不是素数就继续循环 { for(int j=2;j<a;j++) { if(a%j==0&&count==1) { Str=a+"="+j+""; a/=j; count++; break;//为了 a继续从2开始取余 } else if(a%j==0&&count!=1) { Str=Str+"x"+j; a/=j; break;//为了 a继续从2开始取余 } } } Str=Str+"x"+a;//如果A是素数就最后加上a } return Str; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int number = in.nextInt(); String result=myMethod(number); System.out.print(result); } }

  

猜你喜欢

转载自www.cnblogs.com/xiaozhushifu/p/10797683.html