#include <iostream> using namespace std; void prim(int m,int n){ if(m>=n){ while(m%n) n++; m/=n; prim(m,n); cout<<n<<endl; } } int main(){ int m=10986; prim(m,2); return 0; }
m%n 表示取餘,餘數爲 0 時表示 n 能整除 m
當 n 不能整除 m 時,m%n 不爲 0,表達式爲真;否則跳出 while
跳出 while 表示找到了 m 的一個因子 n,因此將 m 除以 n,進入遞歸尋找新的因子
由於輸出因子 n 的命令在遞歸之後,因此對重複的因子只會輸出一次
顯然只會輸出素因子