Perfect Number & Prime Number

本文最后更新于:2024年10月25日 下午

Prime number

It is a basic problem for CS students. The part aim to give more intersiting solution.

NO.1

According to Henry, he asks us to not print such as ‘for’, ‘break’,’continue’. Something only python could be used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def is_prime(x):
if x <= 1:
return False
elif x == 2:
return True
elif x % 2 ==0:
return False
else:
i =3
while i * i <= x:
if x % i == 0:
return False
i = i + 2
return True

This is a code only use ‘if’ and ‘while’. Maybe i need to change ‘Ture’ or ‘False’ to ‘1’ and ‘0’.

About the prime, as we as all kown, 1 is not a prime as the prime defination. All even number except 2 is not prime, because they could be int division by 2. So i only to search odd number.

Let x divise i ,i always be an even, if there no x % i=0

so, x must be a prime.

For the condition of while. i only need to while to sqrt{x}. Those factors always show in double. Such as 28=4*7 it has a factor smaller than sqrt{x}, at the same the another is greater than sqrt{x}. So i only to identify a aspect between smaller and greater.

Perfect number

NO.1

Perfect number is a positive integer whose sum of its proper divisiors is equal to one.

Example 1+2+3=6. The 6 is a perfect number.

1
2
3
4
5
6
7
8
9
10
11
def is_perfect(x):
sum = 1
i = 2
while i < x:
if x % i == 0:
sum = sum + i
i = i + 1
if sum == x:
return True
else:
return False

未完待续