fork download
  1. import java.math.BigInteger;
  2. import java.util.BitSet;
  3. import java.util.Scanner;
  4.  
  5. /*
  6. プログラミングのお題スレ Part13
  7. //mevius.5ch.net/test/read.cgi/tech/1549160513/335
  8.  
  9. 335 名前:デフォルトの名無しさん[sage] 投稿日:2019/02/23(土) 12:44:52.28 ID:W0y17tlk
  10. (略)
  11. ちょっと高度化したお題
  12. 素数階乗n#を実装せよ
  13. ただし素数階乗とは与えられた整数n以下のすべての素数の積である
  14. 1#=1
  15. 3#=4#=6
  16. 5#=30
  17. */
  18. class Ideone
  19. {
  20. public static void main(String[] args)
  21. {
  22. try (Scanner in = new Scanner(System.in))
  23. {
  24. while (in.hasNextInt())
  25. {
  26. int n = in.nextInt();
  27. System.out.printf("%d#=%d%n", n, primeFactorial(n));
  28. }
  29. }
  30. }
  31.  
  32. static BigInteger primeFactorial(int n)
  33. {
  34. if (n < 0) throw new IllegalArgumentException();
  35. BigInteger result = BigInteger.ONE;
  36.  
  37. BitSet bs = new BitSet();
  38. int sqrt = (int) Math.sqrt(n);
  39. for (int i = 2; i <= sqrt; i = bs.nextClearBit(i + 1))
  40. {
  41. for (int j = i; j <= n; j += i) bs.set(j);
  42. result = result.multiply(BigInteger.valueOf(i));
  43. }
  44.  
  45. for (int i = bs.nextClearBit(sqrt + 1); i <= n; i = bs.nextClearBit(i + 1))
  46. {
  47. result = result.multiply(BigInteger.valueOf(i));
  48. }
  49.  
  50. return result;
  51. }
  52. }
  53.  
Success #stdin #stdout 0.07s 2184192KB
stdin
1
3
5
10
1000
stdout
1#=1
3#=6
5#=30
10#=210
1000#=19590340644999083431262508198206381046123972390589368223882605328968666316379870661851951648789482321596229559115436019149189529725215266728292282990852649023362731392404017939142010958261393634959471483757196721672243410067118516227661133135192488848989914892157188308679896875137439519338903968094905549750386407106033836586660683539201011635917900039904495065203299749542985993134669814805318474080581207891125910