How to find the prime factor of a number in java

package test;
import java.util.*;
 public class Main {
    public static void main(String[] args) {
    	//①求一个数的质因数的方法  
    			Scanner sc=new Scanner(System.in);
    			long n=sc.nextLong();
    			long ans=1L;
    			for(int i=2;i*i<=n;i++) {
    				if(n%i==0) {
    					System.out.print(i+" ");
    					int exp=0;
    					while(n%i==0) {
    						n/=i;
    						exp++;
    						
    					}
    					if(exp%2!=0) {
    						ans*=i;
    					}
    				}
    			}
    			if(n==1) System.out.println();
    			else System.out.print(n+" ");
    }
}
    

Sample results are as follows:

Guess you like

Origin blog.csdn.net/qq_49174867/article/details/123971167