Check whether the given number is Euclid Number or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to check whether n is Euclid number or not. As we know Euclid numbers are integer which can be represented as 

n= Pn+1

where  is product of first n prime numbers.

So, if the input is like n = 211, then the output will be True n can be represented as 

211=(2×3×5×7)+1

To solve this, we will follow these steps −

  • MAX := 10000
  • primes := a new list
  • Define a function generate_all_primes() . This will take
  • prime := a list of size MAX and fill with True
  • x := 2
  • while x * x < MAX, do
    • if prime[x] is True, then
      • for i in range x * 2 to MAX, update in each step by x, do
        • prime[i] := False
      • x := x + 1
  • for x in range 2 to MAX - 1, do
    • if prime[x] is true, then
      • insert x at the end of primes
  • From the main method do the following:
  • generate_all_primes()
  • mul := 1, i := 0
  • while mul < n, do
    • mul := mul * primes[i]
    • if mul + 1 is same as n, then
      • return True
    • i := i + 1
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

MAX = 10000
primes = []
 
def generate_all_primes():
   prime = [True] * MAX
 
   x = 2
   while x * x < MAX :
      if prime[x] == True:
         for i in range(x * 2, MAX, x):
           prime[i] = False
      x += 1

   for x in range(2, MAX):
      if prime[x]:
         primes.append(x)

def solve(n):
   generate_all_primes()
   mul = 1
   i = 0
 
   while mul < n :
      mul = mul * primes[i]
      if mul + 1 == n:
         return True
      i += 1
   return False

n = 211
print(solve(n))

Input

211

Output

True
raja
Published on 16-Jan-2021 09:22:49
Advertisements