I want to calculate the last 20 leap year for which I have written this code, can this code be further optimized

huangapple go评论103阅读模式
英文:

I want to calculate the last 20 leap year for which I have written this code, can this code be further optimized

问题

  1. package javaHM;
  2. import java.util.*;
  3. public class LeapYear {
  4. public static void main(String[] args) {
  5. Scanner obj = new Scanner(System.in);
  6. System.out.println("Enter Starting Year");
  7. int year = obj.nextInt();
  8. obj.close();
  9. leapFor(year);
  10. }
  11. public static void leapFor(int year) {
  12. int counter = 0;
  13. for (int i = year; counter < 20; i--) {
  14. if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
  15. System.out.println(i);
  16. counter++;
  17. }
  18. }
  19. }
  20. }
英文:
  1. package javaHM;
  2. import java.util.*;
  3. public class LeapYear {
  4. public static void main(String[] args) {
  5. // TODO Auto-generated method stub
  6. Scanner obj = new Scanner(System.in);
  7. System.out.println(&quot;Enter Starting Year&quot;);
  8. int year = obj.nextInt();
  9. leapFor(year);
  10. obj.close();
  11. }
  12. public static int leapFor(int year) {
  13. int counter = 0, i;
  14. for (i = year; i &gt;= 1; i--) {
  15. if ((i % 4 == 0) &amp;&amp; i % 100 != 0 || i % 400 == 0) {
  16. System.out.println(i);
  17. counter++;
  18. }
  19. if (counter == 20)
  20. break;
  21. }
  22. return i;
  23. }
  24. }

I want to optimize this portion of code , please help me

答案1

得分: 0

您的函数在每次迭代中执行I/O操作。I/O操作速度较慢,因此具有最大影响的优化是将输出累积到缓冲区中,然后仅在最后一次打印。对算法的任何更改都不会产生有意义的差异。

  1. public static int leapFor(int year) {
  2. int counter = 0, i;
  3. StringBuilder output = new StringBuilder(20*(4+1));
  4. for (i = year; i >= 1; i--) {
  5. if ((i % 4 == 0) && i % 100 != 0 || i % 400 == 0) {
  6. output.append(i).append('\n');
  7. counter++;
  8. }
  9. if (counter == 20)
  10. break;
  11. }
  12. System.out.print(output);
  13. return i;
  14. }
英文:

Your function does I/O on every iteration. I/O is slow, so the optimization with the biggest effect is accumulating the output into a buffer, and printing it only once. Any changes to the arithmetic will not make a meaningful difference.

  1. public static int leapFor(int year) {
  2. int counter = 0, i;
  3. StringBuilder output = new StringBuilder(20*(4+1));
  4. for (i = year; i &gt;= 1; i--) {
  5. if ((i % 4 == 0) &amp;&amp; i % 100 != 0 || i % 400 == 0) {
  6. output.append(i).append(&#39;\n&#39;);
  7. counter++;
  8. }
  9. if (counter == 20)
  10. break;
  11. }
  12. System.out.print(output);
  13. return i;
  14. }

huangapple
  • 本文由 发表于 2020年8月7日 01:17:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63288692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定