我的运动需要一些帮助。我得到的代码适用于完美和友好的数字。但它更进一步:
找到1到100000之间的完美和Amicable数字。哪个数字 发生更多?还可以在屏幕上找到它们的频率(1..10000, 10001 ... 20000,20001 ... 30000,30001 ... 40000,40001 ... 50000至100000)完美和友好的数字。
我很难找到他们的频率。我必须使用for
循环。
package amicablefriendlynumbers;
/**
*
* @author sir.
*/
public class Praktika7 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int num=0,sum;
System.out.print("Perfect numbers: ");
for(int i=1; i<=100000; i++){
sum = 0;
//System.out.printf("Numbers %d: %n", i);
for(int Numbers=1; Numbers<i; Numbers++){
if(i%Numbers==0)//{System.out.printf("%d%n",Numbers);}
sum=sum+Numbers;
}
if(sum==i)
{
System.out.printf("%d, ", sum);
}
}
// Here starts amicable numbers.
for(int i=2;i<100000;i++)
{
int k=NumberDivider(i);
if (NumberDivider(k)==i && i!=k)
{
System.out.printf("%nAmicable numbers are %1$d ja %2$d",NumberDivider(i), NumberDivider(k));
}
}
}
public static int NumberDivider(int x)
{
int sum=1;
for (int i=2; i<x; i++)
{
if(x%i==0&&x!=i)
{
sum=sum+i;
}
}
return sum;
}
}
答案 0 :(得分:-1)
您可以设置HashMap来存储频率。你可以这样做:
HashMap<int,int> freqMap = new HashMap<int,int>(100000)
//initialize frequency of all numbers to 0
for(int i =1; i<=100000; i++) {
freqMap.put(i,0);
}
// isAmicable() contains your logic for finding whether x,y are amicable
if(isAmicable(x,y)) {
freqMap(x,freqMap.get(x) + 1);
freqMap(y,freqMap.get(x) + 1);
}
//printing
for(int num : freqMap.keySet()) {
if(freqMap.get(num) !=0) {
System.out.println("number = "+num+" frequency = "+freqMap.get(num));
}
}