LeetCode-Perfect_Number

題目:

We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.

Example:

Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14

Note: The input number n will not exceed 100,000,000. (1e8)


翻譯:

我們定義完美數字是一個正數並且它等於它的所有除數(除了它自己)。

現在,給定一個數字 n,寫下一個函數返回真如果它是一個完美數字,如果它不是返回假。

例子:

輸入: 28
輸出: True
解釋: 28 = 1 + 2 + 4 + 7 + 14

注意: 輸入的數字 n 不超過100,000,000(1e8)


思路:

題目本事不難,但是如果用最簡單的方法,會超時,因此,由於1肯定是因子,提前加上,那麼其他因子的範圍是[2, sqrt(n)]。遍歷這之間的數字 i,首先,如果 i 可以被 n 整除,那麼我們把 i 和 num/i 都加進去;其次,如果 i*i 是 n ,那麼此時的 i 加了兩次,要減掉一個。最後,遍歷過程中如果 sum 大於 n,直接返回false。循環結束後,判斷sum是否等於num。


C++代碼(Visual studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
	bool checkPerfectNumber(int num) {
		if (num <= 0)
			return false;
		if (num == 1)
			return true;
		int sum = 1;
		for (int i = 2; i*i<=num; i++) {
			if (num%i == 0)
				sum += (i+num/i);
			if (i*i == num)
				sum -= i;
			if (sum > num)
				return false;
		}
		return (sum == num);
	}
};

int main()
{
	Solution s;
	int num = 28;
	bool result=s.checkPerfectNumber(num);
	cout << result;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章