hpilo

Chapter4_Loops_Ex16

Dec 15th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. import java.lang.Math;
  2.  
  3.  
  4. /* ==================================
  5. chapter 4: Loops
  6.  
  7. Ex16: friendly numbers
  8. ==================================
  9. */
  10.  
  11. public class MyProgram {
  12.  
  13. /* function to get the sum of divisors */
  14. public static int getSum(int number){
  15.  
  16. int maxD = (int)Math.sqrt(number); //loop's range is [2,√num]
  17. int sum=1; //every number can divide by 1
  18. int divisor; //represent divisors bigger than the search range
  19.  
  20. for(int i = 2; i <= maxD; i++)
  21. {
  22. if(number % i == 0)
  23. {
  24. /*
  25. if i divide the number:
  26. - add i to sum
  27. - init divisor
  28. */
  29.  
  30. sum += i;
  31. divisor = number/i; //must be one of the divisors because the number can divide by i
  32.  
  33. if(divisor!=i) //if the divisor is bigger than the loop's range → add divisor to sum
  34. sum+=divisor;
  35. }
  36. }
  37. return sum;
  38. }
  39.  
  40.  
  41. public static void main(String[] args) {
  42. final int SIZE =10;
  43. int counter = 0;
  44. int num1,num2;
  45.  
  46. for(num1=1;counter<SIZE;num1++){
  47.  
  48. num2=getSum(num1);
  49.  
  50. if( num2>num1 && (num1==getSum(num2) ) ) {
  51. //we found a match! they should get f*** married
  52. System.out.println(num1 + " and " + num2 + " are mates");
  53. counter++;
  54. }
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment