Divisors python что это
Перейти к содержимому

Divisors python что это

  • автор:

Функция divmod() в Python, делит числа с остатком

Функция divmod() возвращает кортеж, содержащий частное и остаток. Не поддерживает комплексные числа. Со смешанными типами операндов применяются правила для двоичных арифметических операторов.

Для целых результат аналогичен (a // b, a % b) .

Для чисел с плавающей запятой результат аналогичен (q, a % b) , где q обычно равен math.floor(a / b) , однако может может быть и на единицу меньше. Так или иначе, q * b + a % b приближено к a , если a % b не нуль, то имеет тот же знак, что и b , и 0

Примеры деление чисел с остатком.

>>> divmod(15, 8) # (1, 7) >>> lst = [x for x in range(1, 10) if x%2] >>> lst # [1, 3, 5, 7, 9] >>> for el in lst: . res = divmod(el, 2) . print(res) . # (0, 1) # (1, 1) # (2, 1) # (3, 1) # (4, 1) 
  • ОБЗОРНАЯ СТРАНИЦА РАЗДЕЛА
  • Функция abs(), абсолютное значение числа
  • Функция all(), все элементы True
  • Функция any(), хотя бы один элемент True
  • Функция ascii(), преобразует строку в ASCII
  • Функция bin(), число в двоичную строку
  • Класс bool(), логическое значение объекта
  • Функция breakpoint(), отладчик кода
  • Класс bytearray(), преобразует в массив байтов
  • Класс bytes(), преобразует в строку байтов
  • Функция callable(), проверяет можно ли вызвать объект
  • Функция chr(), число в символ Юникода
  • Класс classmethod, делает функцию методом класса
  • Функция compile() компилирует блок кода Python
  • Класс complex(), преобразует в комплексное число
  • Функция delattr(), удаляет атрибут объекта
  • Класс dict() создает словарь
  • Функция dir(), все атрибуты объекта
  • Функция divmod(), делит числа с остатком
  • Функция enumerate(), счетчик элементов последовательности
  • Функция eval(), выполняет строку-выражение с кодом
  • Функция exec(), выполняет блок кода
  • Функция filter(), фильтрует список по условию
  • Класс float(), преобразует в вещественное число
  • Функция format(), форматирует значение переменной
  • Класс frozenset(), преобразует в неизменяемое множество
  • Функция getattr(), значение атрибута по имени
  • Функция globals(), переменные глобальной области
  • Функция hasattr(), наличие атрибута объекта
  • Функция hash(), хэш-значение объекта
  • Функция help(), справка по любому объекту
  • Функция hex(), число в шестнадцатеричную строку
  • Функция id(), идентификатор объекта
  • Функция input(), ввод данных с клавиатуры
  • Класс int(), преобразует в тип int
  • Функция isinstance(), принадлежность экземпляра к классу
  • Функция issubclass(), проверяет наследование класса
  • Функция iter(), создает итератор
  • Функция len(), количество элементов объекта
  • Класс list(), преобразовывает в список
  • Функция locals(), переменные локальной области
  • Функция map(), обработка последовательности без цикла
  • Функция max(), максимальное значение элемента
  • Класс memoryview(), ссылка на буфер обмена
  • Функция min(), минимальное значение элемента
  • Функция next(), следующий элемент итератора
  • Класс object(), возвращает безликий объект
  • Функция oct(), число в восьмеричную строку
  • Функция open(), открывает файл на чтение/запись
  • Функция ord(), число символа Unicode
  • Функция pow(), возводит число в степень
  • Функция print(), печатает объект
  • Класс property(), метод класса как свойство
  • Класс range(), генерирует арифметические последовательности
  • Функция repr(), описание объекта
  • Функция reversed(), разворачивает последовательность
  • Функция round(), округляет число
  • Класс set(), создает или преобразовывает в множество
  • Функция setattr(), создает атрибут объекта
  • Класс slice(), шаблон среза
  • Функция sorted(), выполняет сортировку
  • Декоратор staticmethod(), метод класса в статический метод
  • Класс str(), преобразует объект в строку
  • Функция sum(), сумма последовательности
  • Функция super(), доступ к унаследованным методам
  • Класс tuple(), создает или преобразует в кортеж
  • Класс type(), возвращает тип объекта
  • Функция vars(), словарь переменных объекта
  • Функция zip(), объединить элементы в список кортежей
  • Функция __import__(), находит и импортирует модуль
  • Функция aiter(), создает асинхронный итератор
  • Функция anext(), следующий элемент асинхронного итератора

Python math.gcd() Method

Find the greatest common divisor of the two integers:

#Import math Library
import math

#find the the greatest common divisor of the two integers
print (math.gcd(3, 6))
print (math.gcd(6, 12))
print (math.gcd(12, 36))
print (math.gcd(-12, -36))
print (math.gcd(5, 12))
print (math.gcd(10, 0))
print (math.gcd(0, 34))
print (math.gcd(0, 0))

Definition and Usage

The math.gcd() method returns the greatest common divisor of the two integers int1 and int2.

GCD is the largest common divisor that divides the numbers without a remainder.

GCD is also known as the highest common factor (HCF).

Tip: gcd(0,0) returns 0.

Syntax

math.gcd(int1, int2)

Parameter Values

Parameter Description
int1 Required. The first integer to find the GCD for
int2 Required. The second integer to find the GCD for

Technical Details

Return Value: An int value, representing the greatest common divisor (GCD) for two integers
Python Version: 3.5

Python divisors примеры использования

Python divisors — 7 примеров найдено. Это лучшие примеры Python кода для eulerlib.divisors, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.

def solve(): sieve(12000) cache = [0,0,0,0] + [None] * 12001 qty = 0 for d in xrange(4, 12001): cache[d] = twixtQty(d) - sum(cache[div] for div in divisors(d) if div != d) qty += cache[d] return qty
def solve(): sieve(10**6) mdrs = [None] * 10**6 mdrs[0] = 0 # to emulate the omission of 1 from factorizations accum = 0 for n in xrange(2, 10**6): val = max(droot(d) + mdrs[n // d - 1] for d in divisors(n) if d != 1) accum += val mdrs[n-1] = val return accum
def test_divisors_1(self): d = eulerlib.divisors(1) assert d == [1], 'Divisors should be 1'

Finding divisors of a number with Python

Here’s a problem I was trying to solve recently: given an integer n, what are all the divisors of n?

A divisor, also known as a factor, is an integer m which evenly divides n. For example, the divisors of 12 are 1, 2, 3, 4, 6 and 12.

I ended up writing something with itertools, and the code uses a couple of neat bits of number theory. I don’t know if I’ll use it again, but I’m writing it up because it was a fun exercise.

The simplest approach

If we want to find all the numbers that evenly divide n, we could just try every number up to n:

def get_divisors(n): for i in range(1, int(n / 2) + 1): if n % i == 0: yield i yield n 

We only need to go up to n/2 because anything larger than that can’t be a divisor of n – if you divide n by something greater than n/2, the result won’t be an integer.

This code is very simple, and for small values of n this is good enough – but it’s quite inefficient and slow. As n gets bigger, the runtime increases linearly. Can we do better?

Prime factorisations

For my particular project, I was mostly working with factorials. The factorial of n, denoted n! is the product of all the integers up to and including n. For example:

9! = 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1

Because factorials have lots of small factors, I decided to try getting the divisor list by getting smaller factors first. Specifically, I was looking for prime factors – factors which are also prime numbers. (A prime is a number whose only factors are itself and 1. For example, 2, 3 and 5 are prime, but 4 and 6 are not.)

Here’s a function that finds the prime factors of n:

def prime_factors(n): i = 2 while i * i  n: if n % i == 0: n /= i yield i else: i += 1 if n > 1: yield n 

This is similar to the function above, using trial division – we keep trying factors, and if we find one, we divide it away and keep going. Otherwise, we try a higher number. This is a fairly standard approach to finding prime factors.

Once we have it, we can use it to write the prime factorisation of a number – that is, writing the number as a product of primes. For example, the prime factorisation of 9! is:

9! = 2 7 × 3 4 × 5 × 7

Computing this factorisation is relatively efficient, especially for factorials – because the prime factors are all very small, you don’t need many divisions to be done.

There’s a result in number theory called the fundamental theorem of arithmetic which states that prime factorisations are unique – for any number n, there’s only one way to write it as a product of primes. (I won’t write a proof here, but you can find one on Wikipedia.)

This gives us a way to find divisors – by finding all the combinations of prime factors. The prime factors of any divisor of n must be a subset of the prime factors of n, or it wouldn’t divide n.

Going from a prime factorisation to divisors

First, let’s get the prime factors “with multiplicity” (the prime factors, and how many times each factor appears in the prime factorisation):

import collections def get_divisors(n): pf = prime_factors(n) pf_with_multiplicity = collections.Counter(pf) . 

Then, let’s go ahead and construct all the powers of each prime that might appear in a possible divisor of n.

def get_divisors(n): . powers = [ [factor ** i for i in range(count + 1)] for factor, count in pf_with_multiplicity.items() ] 

For example, for 9! this would give us

[ [1, 2, 4, 8, 16, 32, 64, 128], // 2^0, 2^1, . 2^7 [1, 3, 9, 27, 81], // 3^0, 3^1, . 3^4 [1, 5], [1, 7], ] 

Then to combine these into divisors, we can use the rather nifty itertools.product, which takes a series of iterables, and spits out all the ordered combinations of the different iterables it receives. It selects one entry from each list of prime powers, and then by multiplying them together we get a divisor of n.

import itertools def prod(iterable): result = 1 for i in iterable: result *= i return result def get_divisors(n): . for prime_power_combo in itertools.product(*powers): yield prod(prime_power_combo) 

And thus, we have the divisors of n (although unlike the original function, they’re not in sorted order).

Putting it all together

Putting that all together gives this function for getting the divisors of n:

import collections import itertools def prime_factors(n): i = 2 while i * i  n: if n % i == 0: n /= i yield i else: i += 1 if n > 1: yield n def prod(iterable): result = 1 for i in iterable: result *= i return result def get_divisors(n): pf = prime_factors(n) pf_with_multiplicity = collections.Counter(pf) powers = [ [factor ** i for i in range(count + 1)] for factor, count in pf_with_multiplicity.items() ] for prime_power_combo in itertools.product(*powers): yield prod(prime_power_combo) 

This particular implementation is very efficient when you have lots of small prime factors, like the factorials I was working with. I don’t know how well it performs in the general case – and if you’re doing proper scientific computing, I’m sure there are pre-existing, optimised routines for this sort of thing.

But as a fun little exercise? I enjoyed it, and it was nice to dip my toes into number theory again.

By Alex Chan. If you like what I do, perhaps say thanks ?

Except where otherwise noted, this site is dual-licensed as CC BY 4.0 and MIT .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *