首页 > 解决方案 > 使用 while 循环可被 3 整除的第一个偶数 n 的总和

问题描述

前 N 个也能被 3 整除的偶数之和。因此,如果输入是 5,则前 N 个偶数是 0、2、4、6、8。在这 5 个数字中,只有 6 个能被 3 整除,所以输出将是 6。这是我到目前为止所尝试的:

import java.util.Scanner;

public class Exercise1_3 {

   public static void main(String[] args) {

      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int sum = 0;

      int count=0;

      while(count<n){
         // I am stuck here
         System.out.print(sum+" ");
         sum=sum+2;
         count++;
      }

   }
}
input: 5
// (0, 2, 4, 6, 8) only 6 divides by 3 thus
output: 6 

标签: javaloopssum

解决方案


我发现您的代码有几个问题:

  1. 你总是在总和上加 2,而不是把能被 3 整除的数字相加。
  2. 你永远不会检查这个数字是否能被三整除。您可以使用类似的代码进行检查n % 3 == 0

试试这个代码:

import java.util.Scanner;

public class Exercise1_3 {

    public static void main(String[] args) {

        // Read the input.
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        // Loop over the first n even numbers.
        int sum = 0;
        int count = 0;
        while (count < n) {
            int nextEven = 2 * count;

            // If the number is divisible by 3, then add to the running sum.
            if (nextEven % 3 == 0) {
                sum += nextEven;
            }

            count++;
        }

        // Print the output.
        System.out.println(sum);
    }
}

推荐阅读