力扣_數學
阿新 • • 發佈:2022-03-08
Fizz Buzz
//迴圈判斷1~n是否是3和5的倍數 class Solution { public List<String> fizzBuzz(int n) { //設定返回的字串 List<String> str = new ArrayList<String>(); //迴圈判斷1~n是否是3和5的倍數 for(int i = 1;i <= n;i++){ if((i % 3 == 0) && (i % 5 == 0)){ str.add("FizzBuzz");計數質數
//超出時間限制 // //質數的判斷是,如果有任意一個比其小的數大於等於2(2除外)能夠做餘數為0,那麼這個數就不是質數//因為質子是某個數的倍數,2、3等肯定是最小倍的質數,那麼它們的倍數一定都不是質數 //那麼可以從前往後捋,將其設定成可以做餘數的 class Solution { public int countPrimes(int n) { //消除特殊情況 if(n == 0 || n == 1 || n == 2){ return 0; } //設定陣列用於判斷是否為質數 int[] pd = new int[n+1]; //假設都為質數 Arrays.fill(pd,1); //設質數的個數 int rev = 0; for(int i = 2;i < n;i++){ if(pd[i] == 1){ ++rev; if((long)i*i < n){ for(int j = i * i;j < n;j = j+i){ pd[j] = 0; } } } } return rev; } }