简体   繁体   中英

I want to find the 10 first Amicable Pair with only use of arrays, loops and conditions but I'm very new to java and programming in general

I think I know how to enter the sum of division into cell on the array but stuck on how to compare between the arrays and print the 10 pairs.

My code so far:

public static void main(String[] args) {
    int sum1=0,sum2=0;
    int[] arr1=new int[67000];
    int[] arr2=new int[67000];
    for(int i =0;i<=10;i++){
        for(int j =1;j<arr1.length;j++){
            for(int k =0;k<j;k++){
                if(j%k==0){
                    sum1+=k;
                }
            }arr1[j]=sum1;
        }
        for(int j =1;j<arr2.length;j++){
            for(int k =0;k<j;k++){
                if(j%k==0){
                    sum2+=k;
                }
            }arr2[j]=sum2;
        }
    }

} 

You are calculating the same values in both the arrays. Just create the array once.

for (int j = 2; j < arr.length; j++) {
    int sum = 0;
    for (int k = 1; k < j; k++) {
        if (j % k == 0) {
            sum += k;
        }
    }
    arr[j] = sum;
}

Now, here, arr[n] is the sum of the proper divisors of a number n .

We can compare the pairs by looping through arr as:

int cnt = 0, first = 2;

while(cnt < 10) {
   int second = arr[first]; 
   if (second >= arr.length) {
        continue;
   }

   if (second > first) {
      if (first == arr[second]) {
          System.out.printf("%d %d\n", first, second);
          cnt++;
      }
   }
   first++;
   if (first >= arr.length) {
        break;
   }
}

The first check is to avoid overrunning the array index, the second > first check is to make sure we only look forward and not rediscover a pair twice.

And then the main check is first == arr[second] which is what amicable numbers are. What it's saying is that if the sum of divisors of the second number which in fact is the sum of divisors of the first number is the first number itself, then the numbers are amicable pairs.

Side Note: The program could probably be written in other better ways. For example when finding the sum, looping up to the square root of the number in question is enough as the divisors mirror each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM