问题描述
我试图弄清楚这一点。如何写一个java程序,发现友好的对低于一定值,即10000,所以它必须从0比较所有号码在对方的限制,并找出哪些是友好的对。然后,我必须有一个2列矩阵的输出。
我理清计算某个数的适当除数的公式,然后总结一下。
但我不能用for循环,将数字比较起来,并最终输出,这将给我的结果作为2列的矩阵走得更远。
到目前为止,我是由多种因素或分隔的总和,这是我
公共类友善{
公共静态INT sumfactors(INT N){
INT总和= 0;
对于(中期息= 1; DIV< = N; DIV ++)
{
如果(N%DIV == 0)
{
总和+ = DIV;
}
}
返回总和-N;
}
}
首先,您可以改善方法的性能:
私有静态诠释sumFactors(INT N)
{
INT总和= 0;
对于(中期息= 1; DIV< = N / 2; DIV +)
{
如果(N%DIV == 0)
{
总和+ = DIV;
}
}
返回总和;
}
然后,您可以添加以下方法到类:
私有静态诠释[] [] getMatrix(INT限制)
{
INT []数组=新INT [极限]
的for(int i = 2; I<限制;我++)
阵列[I] = sumFactors(ⅰ);
地图<整数,整数GT;图=新的HashMap<整数,整数GT;();
的for(int i = 2; I<限制;我++)
{
INT J =数组[我]
如果(J< I和&安培;我==阵列[J]。)
map.put(I,J);
//检查J<我为了:
// 1时,避免非法索引'J> =限制'
// 2.避免相当于对的插入[J,I]
// 3.避免完美的数字,例如插入[6,6]
}
INT [] []矩阵=新INT [map.size()] [2];
INT索引= 0;
对于(INT键:map.keySet())
{
矩阵[指数] [0] =键;
矩阵[指数] [1] = map.get(密钥);
指数++;
}
返回矩阵;
}
最后,你可以从你的主要方法(例如)调用它:
公共静态无效的主要(字串[] args)
{
INT [] []矩阵= getMatrix(10000);
的for(int i = 0; I< matrix.length;我++)
的System.out.println(矩阵[I] [0] ++矩阵[I] [1]);
}
I am trying to figure this out. How to write a java program that finds the amicable pairs under a certain value, i.e 10000, so it has to compare all numbers from 0 to that limit within each other, and find out which are the amicable pairs. Then i must have the output as a 2 column matrix.
I sort out the formula of calculating the proper divisors of a number and then sum it up.
But i can not go further with the for-loop that will compare the numbers together, and the final output which will give me the result as a 2 column matrix.
So far I am by the sum of factors or dividers, and this is what I have
public class Amicable {
public static int sumfactors(int n) {
int sum=0;
for(int div=1; div<=n; div++)
{
if(n%div==0)
{
sum +=div;
}
}
return sum-n;
}
}
First of all, you can improve the performance of your method:
private static int sumFactors(int n)
{
int sum = 0;
for (int div=1; div<=n/2; div++)
{
if (n%div == 0)
{
sum += div;
}
}
return sum;
}
Then, you can add the method below to your class:
private static int[][] getMatrix(int limit)
{
int[] array = new int[limit];
for (int i=2; i<limit; i++)
array[i] = sumFactors(i);
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i=2; i<limit; i++)
{
int j = array[i];
if (j < i && i == array[j])
map.put(i,j);
// Check 'j < i' in order to:
// 1. Avoid an illegal index when 'j >= limit'
// 2. Avoid the insertion of the equivalent pair [j,i]
// 3. Avoid the insertion of perfect numbers such as [6,6]
}
int[][] matrix = new int[map.size()][2];
int index = 0;
for (int key : map.keySet())
{
matrix[index][0] = key;
matrix[index][1] = map.get(key);
index++;
}
return matrix;
}
Finally, you can call it from your main method (for example):
public static void main(String[] args)
{
int[][] matrix = getMatrix(10000);
for (int i=0; i<matrix.length; i++)
System.out.println(matrix[i][0]+" "+matrix[i][1]);
}
这篇关于Java程序在下面找到10000友好的对,让一个2列矩阵的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!