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

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

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

问题

package javaHM;

import java.util.*;

public class LeapYear {

    public static void main(String[] args) {
        Scanner obj = new Scanner(System.in);
        System.out.println("Enter Starting Year");
        int year = obj.nextInt();
        obj.close();
        leapFor(year);
    }

    public static void leapFor(int year) {
        int counter = 0;
        for (int i = year; counter < 20; i--) {
            if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
                System.out.println(i);
                counter++;
            }
        }
    }
}
英文:
package javaHM;

import java.util.*;

public class LeapYear {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner obj = new Scanner(System.in);
		System.out.println(&quot;Enter Starting Year&quot;);
		int year = obj.nextInt();
			leapFor(year);
			
		obj.close();

	}

	public static int leapFor(int year) {
		int counter = 0, i;
		for (i = year; i &gt;= 1; i--) {
			if ((i % 4 == 0) &amp;&amp; i % 100 != 0 || i % 400 == 0) {
				System.out.println(i);
				counter++;

			}
			if (counter == 20)
				break;
		}
		return i;

	}
}

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

答案1

得分: 0

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

public static int leapFor(int year) {
    int counter = 0, i;
    StringBuilder output = new StringBuilder(20*(4+1));
    for (i = year; i >= 1; i--) {
        if ((i % 4 == 0) && i % 100 != 0 || i % 400 == 0) {
            output.append(i).append('\n');
            counter++;
        }
        if (counter == 20)
            break;
    }
    System.out.print(output);
    return i;
}
英文:

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.

public static int leapFor(int year) {
    int counter = 0, i;
    StringBuilder output = new StringBuilder(20*(4+1));
    for (i = year; i &gt;= 1; i--) {
        if ((i % 4 == 0) &amp;&amp; i % 100 != 0 || i % 400 == 0) {
            output.append(i).append(&#39;\n&#39;);
            counter++;

        }
        if (counter == 20)
            break;
    }
    System.out.print(output);
    return i;
}

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:

确定