我需要找到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 ......
答案 0 :(得分:0)
/* 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;
}
}
}
这将打印出您想要的内容。
答案 1 :(得分:0)
继续将最后一个因子保存在变量中,并在获得下一个因子时将其减去。
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;
}
}