iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0

Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.

An integer m is a divisor of n if there exists an integer k such that n = k * m


翻譯時間!

  • divisor=因數
    題目乍看之下粉簡潔明瞭,就是一個數字n如果存在 剛好3個 因數就返回成功;反之則否。
    一般來說,所有數字n都會至少有兩個因數(1及n)
    若只能有剛好三個因數,那n一定是一個質數p的平方數(因數為1,p,n)

public class Solution {
public static boolean isThree(int n) {
int sqrt_n = (int) Math.sqrt(n);
if (sqrt_n * sqrt_n != n) {
return false;
}
// 判斷sqrt_n是否為質數
if (sqrt_n <= 1) return false;
for (int i = 2; i * i <= sqrt_n; i++) {
if (sqrt_n % i == 0) {
return false;
}
}
return true;
}
}


丟去leetcode檢查結果!
https://ithelp.ithome.com.tw/upload/images/20240922/201694326V1k9lnQoB.png
成功啦!下課!


上一篇
day-6[easy.1893]check if all the integers in a range are covered
下一篇
day-8[medium.2012]sum of beauty in the array
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言