Advertisement
Guest User

Untitled

a guest
Feb 14th, 2012
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. import java.util.HashSet;
  2. import java.util.Set;
  3.  
  4.  
  5. public class Divisors {
  6.  
  7. Set[] d;
  8. int[] s;
  9. int n;
  10.  
  11. public Divisors(int n) {
  12.  
  13. this.n = n;
  14. d = new Set[n + 1];
  15. s = new int[n + 1];
  16.  
  17. for (int i = 1; i <= n; i++) {
  18. d[i] = new HashSet();
  19. }
  20.  
  21. for (int i = 1; i <= n; i++) {
  22. seive(i);
  23. }
  24. }
  25.  
  26. private void seive(int toSeive) throws IllegalArgumentException {
  27.  
  28. if (toSeive < 1) {
  29. throw new IllegalArgumentException();
  30. }
  31.  
  32. for (int i = toSeive; i <= n; i+=toSeive) {
  33. if (d[i].add(new Integer(toSeive)) && i!=toSeive) {
  34. s[i] += toSeive;
  35. }
  36. }
  37. }
  38.  
  39. private void printD() {
  40.  
  41. for (int i = 1; i <= n; i++) {
  42. System.out.println(i + ": " + d[i] + " Sum: " + s[i]);
  43. }
  44. }
  45.  
  46. private void computePerfectsAndPairs() {
  47.  
  48. for (int i = 1; i <= n; i++) {
  49. if (s[i] == i) {
  50. System.out.println("Perfect number " + i + ": " + d[i]);
  51. }
  52.  
  53. if (s[i] > 0 && s[i] <= n && i < s[i] && i == s[s[i]]) {
  54. System.out.println("Amicable pair " + i + " and " + s[i]
  55. + ": " + d[i] + " " + d[s[i]]);
  56. }
  57. }
  58. }
  59.  
  60. public static void main(String[] args) {
  61.  
  62. Divisors d = new Divisors(10000);
  63. // d.printD();
  64. d.computePerfectsAndPairs();
  65. }
  66. }
  67.  
  68.  
  69. Perfect number 6: [1, 2, 3, 6]
  70. Perfect number 28: [1, 2, 4, 7, 28, 14]
  71. Amicable pair 220 and 284: [220, 1, 2, 55, 4, 20, 5, 22, 110, 10, 11, 44] [1, 2, 71, 4, 142, 284]
  72. Perfect number 496: [16, 1, 2, 4, 248, 8, 124, 496, 62, 31]
  73. Amicable pair 1184 and 1210: [592, 16, 1, 32, 2, 1184, 4, 37, 296, 8, 148, 74] [1, 2, 55, 5, 22, 1210, 110, 10, 11, 605, 242, 121]
  74. Amicable pair 2620 and 2924: [1, 655, 2, 262, 4, 1310, 20, 5, 524, 131, 10, 2620] [68, 34, 17, 1, 2, 731, 86, 4, 1462, 172, 43, 2924]
  75. Amicable pair 5020 and 5564: [1255, 2510, 1, 2, 5020, 4, 1004, 251, 20, 5, 502, 10] [1, 2, 1391, 4, 428, 2782, 52, 214, 26, 5564, 107, 13]
  76. Amicable pair 6232 and 6368: [1, 2, 4, 38, 8, 76, 41, 6232, 164, 152, 19, 3116, 82, 1558, 779, 328] [16, 1, 32, 2, 4, 398, 1592, 8, 199, 796, 6368, 3184]
  77. Perfect number 8128: [508, 1016, 2032, 1, 4064, 8128, 2, 32, 4, 64, 8, 254, 16, 127]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement