我需要找到n= 20的因子,我的代码如下所示。
int n=20;
for (int i = 1; i <= n; i++) {
if(n%i==0){
System.out.println(i+" ,");
}
}它产生结果1,2,4,5,10,20
但是我怎么才能找到每个相邻数字的差异呢?比如1-2=-1,2-4=-2...
发布于 2018-04-25 19:53:34
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int n=20;
int a = 0;
int b = 0;
for (int i = 1; i <= n; i++) {
if(n%i==0){
b = i;
if(a!=0)
System.out.println(a - b+" ,");
a = i;
}
}
}这将打印出您想要的内容。
发布于 2018-04-26 11:34:34
将最后一个因子保存在一个变量中,并在得到下一个因子时减去它。
int n = 20;
//1 is the factor of every no.
//So let's assign 1 to the first variable
int last = 1;
for(int i=2; i<=n; i++) {
if(n%i==0) {
//i is the factor of n:
System.out.print((i-last) + " ");
//Save the this factor to use next:
last = i;
}
}https://stackoverflow.com/questions/50021113
复制相似问题