Problem Statement :Problem21
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
Approach:
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a  b, then a and b are an amicable pair and each of a and b are called amicable numbers.
 b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
Approach:
- Function getvalue will return the value of all divisors of a number
- Call it twice and and just check whether they are equal or not.
public class problem21 {
 public static int isPrime(int n1) {
  int num = n1;
  for (int i = 2; i <= Math.sqrt(num); i++) {
   if (num % i == 0)
    return i;
  }
  return 0;
 }
 static int getvalue(int num) {
  if (isPrime(num) == 0)
   return 1;
  int value = 0;
  for (int i = 1; i <= num / 2; i++) {
   if (num % i == 0)
    value = value + i;
  }
  return value;
 }
 public static void main(String args[]) {
  int n = 10000, sum = 0;
  for (int i = 2; i < n; i++) {
   int val = getvalue(i);
   int revval = getvalue(val);
   if (i == revval && val != i)
    sum = sum + revval;
  }
  System.out.println(sum);
 }
}
 
No comments:
Post a Comment