如何找到一些与循环的因素是什么? [英] How to find the factors of a number with for loops?
问题描述
嘿,我需要一些帮助,我的AP的计算机科学功课。在任务,我需要打印传递的变量,z的因素。这是我在我的方法,到目前为止得到
Hey I need some help with my AP Comp Sci homework. In the assignment I need to print the factors of a passed variable, z. This is what I've gotten so far in my method
public static void printFactors(int z) {
for(int x=1; x<=z; x++) {
if(z%x.......) {
System.out.println(x);
}
}
}
我将如何完成呢?还是我即使是在正确的轨道上?谢谢!
How would I go about finishing this? Or am I even on the right track? Thanks!
推荐答案
至于你的问题,你想获得的所有的因素,我可能会认为,你想要的完整列表,但一个明显的因素整数。
As your question, you want to get ALL factors, I might think, you want the full list, but distinct factors of an integer.
所以,你只能遍历从1整数x为的sqrt(Z)
,但SQRT本身就是太慢了,你可以循环x直到 X * X&GT; ž
,见下面循环。
So, you can only iterates the integer x from 1 to sqrt(z)
, but sqrt itself is too slow, and you can loop x until x*x > z
, see the for loop below.
更多,你应该注意,如果以Z%×== 0
More, you should take care that if z % x == 0
例如:Z = 18,X = 3,Z%X = 0
for example: z = 18, x =3, z % x = 0
则z / x必须也是一个因素,太!它应该是输出
then z / x must be also a factor, too! It should be output.
但要避免产生重复的因素,如果以Z = = X * X
,然后 X == Z / X
,这两个因素 X
和 Z / X
是重复的,它应该只被输出一次。
but to avoid duplicated factors produced, if z == x * x
, then x == z / x
, the two factors x
and z/x
is duplicate, it should only be output once.
这是一个经典算法问题,这个实现是普遍使用的一种,它与时间复杂度 O(开方(Z))
。
This is a classical algorithm issue, and this implemetation is the generally used one, which with time complexity O(sqrt(z))
.
见code:
public static void printFactors(int z) {
for(int x=1; x * x <= z; x++) {
if(z % x == 0) {
System.out.println(x);
if(x * x != z) System.out.println(z / x);
}
}
}
有一个尝试!
Have a try!
这篇关于如何找到一些与循环的因素是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!