fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int n = 500;
  13. System.out.println(n + "個以上の約数を持つ最初の三角数は" + func(n));
  14. }
  15.  
  16. public static int func(int num) {
  17. // 2番目の三角数2*3/2=3に対応する、low:2/2=1の約数の個数1、high:3の約数の個数2
  18. int low = 1;
  19. int high = 2;
  20. int n = 2;
  21. while (low * high < num) {
  22. n++;
  23. low = high;
  24. high = numOfDivisor(n + 1);
  25. }
  26. return n * (n + 1) / 2;
  27. }
  28.  
  29. private static int numOfDivisor(int n) {
  30. if (n < 2) return 1;
  31. int answer = 1;
  32.  
  33. // 偶数だった場合は2で割る(ビットシフト)
  34. if ((n & 1) == 0)
  35. n >>= 1;
  36.  
  37. // nが√Integer.MAX_VALUE以上の素数だったりすると、この継続条件は良くないが、
  38. // 簡単なのでこちらで進める
  39. for (int i = 2; i * i <= n; i++) {
  40. int count = 0;
  41. while (n % i == 0) {
  42. n /= i;
  43. count++;
  44. }
  45. answer *= count + 1;
  46. }
  47. // forを抜けて残ったnが1でないときは、そのnは素数なので1+1=2を掛ける
  48. if (n != 1)
  49. answer *= 2;
  50. return answer;
  51. }
  52. }
Success #stdin #stdout 0.09s 28012KB
stdin
Standard input is empty
stdout
500個以上の約数を持つ最初の三角数は76576500