Java程式:檢查是否可以使用陣列中的所有數字構成一個能被3整除的數


要檢查是否可以使用陣列中的所有數字構成一個能被3整除的數,Java程式碼如下:

示例

 線上演示

import java.io.*;
import java.util.*;
public class Demo{
   public static boolean division_possible(int my_arr[], int n_val){
      int rem = 0;
      for (int i = 0; i < n_val; i++)
         rem = (rem + my_arr[i]) % 3;
      return (rem == 0);
   }
   public static void main(String[] args){
      int my_arr[] = { 66, 90, 87, 33, 123};
      int n_val = 3;
      if (division_possible(my_arr, n_val))
         System.out.println("It is possible to make a number that can be divided by 3");
      else
         System.out.println("It is not possible to make a number that can be divided by 3");
   }
}

輸出

It is possible to make a number that can be divided by 3

名為Demo的類包含一個名為“divide_possible”的函式。它檢查是否可以使用這些數字構成一個能被3整除的數。在主函式中,定義了一個帶有值的陣列和一個“n”值。該函式使用特定引數呼叫,相關訊息將顯示在控制檯上。

更新於:2020年7月8日

173 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.