[英]How to find prime factorization of number using loop?
我应该找到这个数字的质因数分解:600851475。
根据我的老师和这个网站http://www.mathsisfun.com/prime-factorization.html 的说法,素数分解是素数乘以得到那个数字。 因此,例如 12,即使它的因数是 2、3、4、6,素因数也不会只是 2 和 3,而是 2、2、3。
我已经有了找到素因数的算法,但我找不到循环的方法,以便它不断找到其余的,直到没有更多的素因数。
这是我得到的:
public class primeFactors {
public static void main(String[] args) {
int d= 600851475;
int i = 2;
if (d%i!=0) {i++;}
if (d%i==0) {d=d/i;}
System.out.println(i);
}
}
它打印出这个:3。
如果我多次复制粘贴它会打印不同的东西:
public class primeFactors {
public static void main(String[] args) {
int d= 600851475;
int i = 2;
if (d%i!=0) {i++;}
if (d%i==0) {d=d/i;}
System.out.println(i);
if (d%i!=0) {i++;}
if (d%i==0) {d=d/i;}
System.out.println(i);
if (d%i!=0) {i++;}
if (d%i==0) {d=d/i;}
System.out.println(i);
if (d%i!=0) {i++;}
if (d%i==0) {d=d/i;}
System.out.println(i);
}
}
那个打印:3, 3, 4, 5, 5。我怎样才能用循环来做到这一点? 我尝试使用 do while 循环( do { if section} while (d>i) {print i} ),但它不起作用。 我也试过 for 循环 (i=2;i<=d;i++) & 它不起作用。 它也给了我合数。 请帮忙!!
由于这是一项作业,因此我最多只能给你一个大致的方向:写这个的最简单方法是尝试候选除数并减少。 例如:
130 - 尝试 2,它会分开,所以减少 65 - 也许那里还有另外 2? 再试2。 它不会分裂,所以继续 65 - 尝试 3 - 不。 4? 不。 5? 是的,它会分裂,所以减少。 13 - 里面还有 5 个吗? 不。 尝试 6, 7, 8, 9, 10, 11, 12. 好的,你完成了。
因此,您需要在循环中尝试候选除数,并且需要一个内部循环来确保排除任何重复的因数(例如,525 将具有质因数 3、5 和 7,但您仍然想摆脱那第二个5)。 这应该让你走上正轨。
显然,会有更有效的方法来编写它,但是如果您遇到困难,请从最简单的可行方法开始,然后让它发挥作用。
你只需要这样的东西(也许这不是最有效的方法,但它非常简单易懂):
int d= 600851475;
for (int i = 2 ; i < (d / 2) ; i++){
if(isPrime(i)){
if(d % i ==0){
System.out.println(i + "Is a prime factor of " + d);
}
}
}
但首先你需要有这个方法来检查它是否是素数
public static boolean isPrime(int n){
for(int i = 2 ; i < n ; i++){
if(n % i == 0){
return false;
}
}
return true;
}
尝试使用 for 循环。
for (int i = 2; i <= d; i++)
{
//implement if statement here
}
这应该为您指明正确的方向。
你有正确的想法。 您需要对每个因子进行除法,直到它不再除法为止。
// this will print all prime divisors for n
for (int i = 2; n != 1; i++)
{
while (n % i == 0)
{
System.out.println (i);
n /= i;
}
}
如何找到一个数的质因数分解?
这是我尝试过的:
def p_factorization(n):
#Finding the factors of n.
num=[i for i in range(1,n+1) if n%i==0]
#Finding the prime factors of n.
#Now prime_num checks to see if any of the factors of 36 have more than two "subfactors".
prime_num=[i for i in range(2,max(num)) if len([j for j in range(1,i+1) if i%j==0])<=2 and max(num)%i==0]
return prime_num
#Explanation:
#The num list is self-explanatory. It finds all of the factors of the number n.
#The prime_num list comprehension is where it gets complicated:
#The i represents all of the numbers in the range of the original factors that we found,
#then we know that a number is prime if it has two or fewer factors, hence the if condition
#applying to the len of the factors of i, which is being iterated through.
#For example, 4 is not a prime number because the length of the list of factors is
#3 [1,2,4].
当然,我们仍然需要 max(num) 可以被 i 整除。
不客气!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.