Input =
Array [] a = {1,2,3,6,9,4};
output:
Output 1 : need to print pair of number with square and squareroot
e.g. 2 , 4
3 , 9
Output 2 : unpaired number : 1 and 6 for which we dont have any square root pair.
我正在编写下面的代码以获得第一部分的输出:
int [] sample = {9, 4 ,3 ,2, 6 , 1};
for (int i =0 ;i <sample.length ; i++){
int square = sample [i] * sample[i];
double mathsq = Math.sqrt(sample[i]);
for ( int j= 0; j< sample.length ; j ++){
if (sample[j] == square && sample[j] != sample [i]) {
System.out.println(sample[i] + "==> " + sample[j]);
}
}
}
无法找到第二种情况的登录信息..
所以我用下面的代码找到了解决方案,我创建了一个ArrayList来存储具有平方根和平方关系的元素,然后将其与现有数组进行比较。
下面是代码片段
public class Demo {
public static void main(String[] args){
int [] sample = {9, 4 ,3 ,2, 6 , 1};
ArrayList<Integer> newarr = new ArrayList<>();
for (int i =0 ;i <sample.length ; i++){
int square = sample [i] * sample[i];
for ( int j= 0; j< sample.length ; j ++){
if (sample[j] == square && sample[j] != sample [i]) {
System.out.println(sample[i] + "==> " + sample[j]);
newarr.add(sample[i]);
newarr.add(square);
}
}
}
System.out.println("Unpaired : ");
for (int i =0 ;i <sample.length ; i++) {
if (!newarr.contains(sample[i])) {
System.out.print(sample[i] + " , ");
}
}
}
}