如何编写计算一个数的因数的 Java 程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13792404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I write a Java program that calculates the factors of a number?
提问by user1029481
I need help thinking up a formula for finding the factors of a number:
我需要帮助想出一个公式来找到一个数的因数:
Write a method named printFactors that accepts an integer as its parameter and uses a fencepost loop to print the factors of that number, separated by the word " and ". For example, the number 24's factors should print as:
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
You may assume that the number parameter's value is greater than 0.
编写一个名为 printFactors 的方法,该方法接受一个整数作为其参数,并使用 fencepost 循环打印该数字的因子,用单词“和”分隔。例如,数字 24 的因数应打印为:
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
您可以假设 number 参数的值大于 0。
Please don't give me a COMPLETE program as I would like to try it out myself.
请不要给我一个完整的程序,因为我想自己尝试一下。
The current code I have has a for loop to control the number of "and's" appearing, however, I printed out the last number by itself since I don't want a "24 and" attached to it... So the output looks something like this at the moment: "1 and 2 and 3" (I haven't yet thought up the equation hence the 1,2,3...)
我的当前代码有一个 for 循环来控制出现的“and's”的数量,但是,我自己打印了最后一个数字,因为我不想在上面附加一个“24 and”......所以输出看起来目前是这样的:“1 和 2 和 3”(我还没有想出等式,因此 1,2,3 ......)
I'm currently thinking that the factors requires a % kind of formula right? Will I need division? I was also thinking of printing out 1 and whatever the number (in this case, 24) you are finding factors for, since 1 and the number itself are always factors of itself. What else am I missing??
我目前认为这些因素需要一种 % 的公式,对吗?我需要分裂吗?我还想打印出 1 以及您正在寻找因数的任何数字(在本例中为 24),因为 1 和数字本身始终是其自身的因数。我还缺少什么??
Thanks in advance!! :)
提前致谢!!:)
回答by ChrisW
I'm currently thinking that the factors requires a % kind of formula right?
我目前认为这些因素需要一种 % 的公式,对吗?
Yes.
是的。
I was also thinking of printing out 1 and whatever the number (in this case, 24) you are finding factors for, since 1 and the number itself are always factors of itself.
我还想打印出 1 以及您正在寻找因数的任何数字(在本例中为 24),因为 1 和数字本身始终是其自身的因数。
If you test every number from 1 to n (e.g. from 1 to 24) then 1 and the number itself don't need to be special cases (because they'll simply satisfy your ordinary "% kind of formula").
如果您测试从 1 到 n(例如从 1 到 24)的每个数字,那么 1 和数字本身不需要是特殊情况(因为它们只会满足您普通的“% 类型的公式”)。
Maybe 1 is a special case because it doesn't have the word "and" in front of it.
也许 1 是一个特例,因为它前面没有“和”这个词。
What else am I missing??
我还缺少什么??
This may be more complicated than you want, but to find all the factors of n you only need to loop up to the square root of n.
这可能比您想要的更复杂,但是要找到 n 的所有因子,您只需要循环到 n 的平方根。