簡體   English   中英

計算整數的素數中每個數字的出現

[英]Counting the occurrence of each number in prime factors of an integer

我想計算一個整數的每個素數的數量。 例如,18 = 2 ^ 1 * 3 ^ 2。 我想得到每個質數的所有指數部分。 對於數字18,它是1 + 2 = 3。
以下是生成整數的所有素數的程序。

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for (int i = 2; i <= n / i; i++) {
        while (n % i == 0) {
            System.out.print(i + ", ");
            n /= i;
        }
    }
    if (n > 1)
        System.out.print(n + ", ");

對於輸入18,此程序將打印2、3、3,...。 至於完成我的要求,要計算每個素數的發生,我可以先將它們全部添加到列表中,然后從列表的開始到結尾的for循環可以計算每個數的出現。 但是這個想法對我來說似乎不好。 對於所有主要因素,我不必要添加一個for循環,這只是告訴我該主要因素在列表中出現了n次。
任何更好的方法來獲取整數的質數的個數。

是的,就像@attila和@robert所說:

import java.util.Scanner; 
import java.util.TreeMap; 

public class Test{
    public static void main( String args[] ){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        TreeMap<Integer, Integer> factors = new TreeMap<Integer, Integer>(); 

        for (int i = 2; i <= n / i; i++) {
            int count = 0; 

            while (n % i == 0) {
                System.out.print(i + ", ");
                n /= i;
                count ++; 
            }
            if( count > 0 ) 
                factors.put( i, count ); 
        }
        if (n > 1){
            System.out.print(n + ", ");
            factors.put( n, 1 ); 
        }
        System.out.println(); 

        System.out.println( "-------------" ); 
        for( Integer factor : factors.keySet() ){
            System.out.println( factor + "^" + factors.get( factor ) ); 
        }
    }
}

我使用樹狀圖,因為它使因子按自然順序排列,這很整潔:)您還可以使用哈希圖,它應該快一點。 但是素數分解的實現應該太慢了,以至於我認為它並不重要:)

每次執行n/=i; ,您遇到了一個因素。 因此,通過在此時增加一個計數器(從0開始),可以在分解過程結束時獲得因子總數。

請注意,如果需要正確處理質數,則需要額外的費用。 對於素數,您找不到任何因數,因此計數器將為0-在這種情況下,您需要在循環后將其設置為1(一個因數:本身)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM