nt.number theory – the gaps between values of a positive binary quadratic form at integer points

Suppose that $s$ is a positive irrational number. Consider all possible values of the sum $x^2+sy^2$ where $x$ and $y$ are integers. These values form a set $W={0=w_1<w_2<ldots}$. Can the gaps $w_{k+1}-w_k$, $k=1,2,ldots$, always remain smaller than a constant $C(s)$?

performance – Iterative uniform recombination of integer lists in python with numba

I have a list of N integers and I iteratively take two integers at random, which are not at the same position in the list and uniformly recombine their binary representation, e.g. in intList = (1,4,1,5) (N=4) the number on the second and third position is chosen, aka 4 & 1, and their binary represenations 4=100 & 1=001 is uniformly recombined. Uniformly recombined means that I chose either the 1 or the 0 of the first position, one of the two 0's of the second position and either the 0 or 1 of the third position. This could result in 000 or 101 or 100 or 001. The result is saved as integer in the list. The update is sequential. This happens in a function with a numba decorator. My code is:

@nb.njit()
def comb():
    iterations = 100000
    N = 1000
    intList = list(range(N))   # this is just an example of possible integer lists
    l = 10   # length of the largest binary representation. 
    intList_temp = (0)*N
    for _ in range(iterations):
        for x3 in range(N):
            intList_temp(x3) = intList(x3)
        for x3 in range(N):
            randint1 = random.randint(0, N - 1)
            randint2 = random.randint(0, N - 1)
            while randint1 == randint2:
                randint1 = random.randint(0, N - 1)
                randint2 = random.randint(0, N - 1)
            a = intList(randint1)
            b = intList(randint2)
            c = a ^ ((a ^ b) & random.randint(0, (1 << l) - 1))
            intList_temp(x3) = c
        for x3 in range(N):
            intList(x3) = intList_temp(x3)
    return intList

print(timeit(lambda: comb(), number=1))
>>>2.59s

My question is, can this be improved?

number theory – Show that 2020 divides $pleft( n right)$ for every integer $n$

Consider:
$$pleft( n right)=800n+400{{n}^{2}}+400{{n}^{4}}+200{{n}^{5}}+100{{n}^{10}}+100{{n}^{20}}+8{{n}^{101}}+4{{n}^{202}}+4{{n}^{404}}+2{{n}^{505}}+{{n}^{1010}}+{{n}^{2020}}$$
Show that: $2020$ divides $pleft( n right)$ for every positive integer $n$?

Work: the statement is indeed true for $n=1,2..100$ , of course using a computer!!

elementary number theory – Show that a prime p divides the sum of polynomials with integer coefficients of degree less than p – 1

Here’s the full question: Let $Finmathbb Z(x)$ be a polynomial of degree less than $p-1$, show that
$$
p | F(0) + F(1) + … + F(p-1)
$$

I don’t really know how I should get started with the problem, I’ve thought about Fermat’s little theorem but since $F$ is of degree less than $p-1$, it doesn’t really apply. Any hints on what theorems I should consider or approach to try would be great, thanks!

python – LeetCode 8: String to Integer (atoi)

I’m posting a solution for LeetCode’s “String to Integer (atoi)”. If you’d like to review, please do. Thank you!

Problem

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ‘ ‘ is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: (−231, 231 − 1). If the numerical value is out of the range of representable values, 231 − 1 or −231 is returned.

Example 1:

Input: str = "42"
Output: 42

Example 2:

Input: str = "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: str = "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: str = "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: str = "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.

Code

from typing import List
import collections
import itertools
import functools
import math
import string
import random
import bisect
import re
import operator
import heapq
import queue

from queue import PriorityQueue
from itertools import combinations, permutations
from functools import lru_cache
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from collections import Counter


class Solution:
    def myAtoi(self, s):
        s = re.findall(r'^s*(+-)?d+', s)
        try:
            MAX, MIN = 2147483647, -2147483648
            res = int(''.join(s))
            if res > MAX:
                return MAX
            if res < MIN:
                return MIN
            return res
        except:
            return 0


if __name__ == "__main__":
    print(Solution().myAtoi("   -42"))

References:

python – Leetcode atoi (string to integer)

link here I’ll include a solution in python and c++ and you can review one, I’m mostly interested in reviewing the c++ code which is a thing I recently started learning, those who don’t know c++ can review python code.

Problem statement

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ‘ ‘ is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: (−231, 231 − 1). If the numerical value is out of the range of representable values, 231 − 1 or −231 is returned.

Example 1:

Input: str = "42"
Output: 42

Example 2:

Input: str = "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: str = "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: str = "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: str = "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.

str_int.py

def convert(s):
    chars = (c for c in s)
    ss = ()
    while True:
        try:
            current = next(chars)
            if (space := current.isspace()) and ss:
                break
            if (pm := current in '+-') and ss:
                break
            if not current.isnumeric() and not pm and not space:
                break
            if not space:
                ss.append(current)
        except StopIteration:
            break
    try:
        number = int(''.join(ss).strip())
        if number < 0:
            return max(-2 ** 31, number)
        return min(2 ** 31 - 1, number)
    except ValueError:
        return 0


if __name__ == '__main__':
    print(convert("    48-"))

There is an overloaded function I call atoi_impl() one version accepts 3 parameters s, start_idx and end_idx and uses std::stoi() to return the result and another that is the proper implementation of atoi and accepts only s but for some reason, it causes a runtime error on leetcode platform only (works perfectly fine on my mbp) so as long as it achieves what it’s meant to do, I might consider it better / more readable.

str_int.h

#ifndef LEETCODE_STR_TO_INT_H
#define LEETCODE_STR_TO_INT_H
#include <string>
int atoi_impl(const std::string& s);
int atoi_impl(const std::string& s, size_t start_idx, size_t end_idx);
int convert_str(const std::string &s);
#endif //LEETCODE_STR_TO_INT_H

str_int.cpp

#include <string>
#include <iostream>


int atoi_impl(const std::string& s) {
    int result = 0;
    size_t i;
    for ((s(0) == '-') ? i = 1: i = 0; s(i) != ''; ++i) {
        auto update = result * 10 + s(i) - '0';
        if (update / 10 != result) {
            result = (s(0) == '-') ? INT32_MIN: INT32_MAX;
            return result;
        }
        result = result * 10 + s(i) - '0';
    }
    result = (s(0) == '-') ? -result: result;
    return result;
}


int atoi_impl(const std::string& s, size_t start_idx, size_t end_idx) {
    try {
        return std::stoi(s.substr(start_idx, end_idx));
    }
    catch (const std::out_of_range &e) {
        return (s(start_idx) == '-') ? INT32_MIN : INT32_MAX;
    }
    catch (const std::invalid_argument &e) {
        return 0;
    }
}


int convert_str(const std::string &s) {
    size_t start_idx = 0;
    size_t end_idx = s.size();
    for (size_t i = 0; i < s.size(); ++i) {
        bool digit = std::isdigit(s(i));
        bool pm = s(i) == '+' || s(i) == '-';
        bool space = std::isspace(s(i));
        if (i == start_idx && !space && !digit && !pm)
            return 0;
        if ((space || !digit) && i != start_idx) {
            end_idx = i;
            break;
        }
        if (space)
            start_idx++;
    }
    if (start_idx != end_idx)
        return atoi_impl(s, start_idx, end_idx);
    return 0;
}


int main() {
    std::cout << "result1: " << convert_str(" -912332") << "n";
}

bugs – NearestNeighborGraph doesn’t show a 3D graph when one or more points are Integer and the rest are Decimal?

Bug introduced in 10.3 or earlier and persisting through 12.1.1


When all the points are the same kind, say Integer then NearestNeighborGraph will display a 3D graph when using {x,y,z} coordinates. However, when just one of those points is say a Decimal instead then one sees a 2D graph. It seems the reverse is true too. For example:

allIntegers = NearestNeighborGraph[{{0,0,0},{-1,1,1},{1,-1,1},{-1,-1,1},{1,1,1},{0,0,2},{0,0,1}},{All,2}];
allDecimals = NearestNeighborGraph[{{0.,0.,0.},{-1.,1.,1.},{1.,-1.,1.},{-1.,-1.,1.},{1.,1.,1.},{0.,0.,2.},{0.,0.,1.}},{All,2}];

oneInteger = NearestNeighborGraph[{{0,0.,0.},{-1.,1.,1.},{1.,-1.,1.},{-1.,-1.,1.},{1.,1.,1.},{0.,0.,2.},{0.,0.,1.}},{All,2}];
oneDecimal = NearestNeighborGraph[{{0.,0,0},{-1,1,1},{1,-1,1},{-1,-1,1},{1,1,1},{0,0,2},{0,0,1}},{All,2}];

Row[{allIntegers, allDecimals, oneInteger, oneDecimal}]

Displays:

2 3D graphs and 2 2D graphs

Is there something I’m doing wrong or some parameter I need to pass? I’d like to be able to force 3D.

php – Incorrect integer value: ” for column `myuser`.`cursantes`.`id_usuario` at row 1

Estoy realizando un sistema que te permita elegir los datos de unas tablas y guardarlas en otra tabla:

Primero seleccionas de un dropdown que usuario queres elegir (tabla usuarios) despues seleccionas de otro dropdown el dato del curso (tabla cursos) todo esto tiene que guardarse en otra tabla que se llama cursantes

agregarCursante.php :

function agregarCursante ()
{
    $link = conectar();
    $id_usuario = $_POST('id_usuario');
    $id_cursada = $_POST('id_cursada');
    $activo = $_POST('activo');
    $sql = "INSERT INTO cursantes (id_usuario, id_cursada, activo ) VALUES ( '".$id_usuario."', '".$id_cursada."', '".$activo."' )";
    $resultado = mysqli_query($link, $sql) or die( mysqli_error($link) );
    return $resultado;
}

Formulario dde seleccion de datos:

<form method="post" action="agregarCursante.php">
                    
        Seleccione alumno:<br>
        <select name="cursantes" id="cursantes">

          <option disabled selected>--Seleccione alumno--</option>
            
          <?php
          $link = conectar();
          $listaCursantes = mysqli_query($link, "SELECT usuarios.id_usuario, usuarios.nomyape, usuarios.email, usuarios.id_categoria, usuarios.activo, cursantes.id_cursante, cursantes.id_cursada, cursantes.id_cursada, usuarioesc.id_escuela
          FROM usuarios
          INNER JOIN cursantes ON usuarios.id_usuario = cursantes.id_usuario
          INNER JOIN usuarioesc ON usuarios.id_usuario = usuarioesc.id_usuario 
          WHERE usuarioesc.id_escuela = '".$id_escuela."' ORDER BY usuarios.id_usuario DESC");

          while($data1 = mysqli_fetch_array($listaCursantes))
          {
              echo "<option value='". $data1('id_usuario') ."'>" .$data1('nomyape') ."</option>";
          } 
          ?>  

        </select>

        <br>Seleccione curso:<br>

        <select name="cursos" id="cursos">

          <option disabled selected>--Seleccione curso--</option>

          <?php
          $link = conectar();
          $listaCursos = mysqli_query($link, "SELECT * FROM cursos ORDER BY id_curso DESC");

          while($data2 = mysqli_fetch_array($listaCursos))
          {
              echo "<option value='". $data2('id_curso') ."'>" .$data2('nombre') ."</option>";
          } 
        ?>  

        </select>

        <br>Estado:<br>

          <select name="activo" id="activo">
            <option value="1">Activo</option>
            <option value="0">Desactivado</option>
          </select>

    <button class="btn btn-dark btn-lg">Inscribir</button>
    <a href="adminCursantesEscuela.php" class="btn btn-outline-secondary btn-lg">Cancelar</a>

</form>

Pero el problema es que salta este mensaje de error (Y no se guarda nada):

Incorrect integer value: ” for column
myuser.cursantes.id_usuario at row 1

Nota: en la tabla de “cursantes” se encuentra una columna que se llama id_cursante y es AUTO_INCREMENT. Y la “id_usuario” que se encuentra en esta misma tabla (cursantes) se toma desde la tabla de usuarios

efficiency – Efficient triangular decomposition of an integer

Euclidean division is an iterative process
that has been made super-efficient at the CPU level, right?

Its specification is that if I do (q, r) = f(n, d), I get super efficient result verifying that n = d * q + r with maximal q.

I need to perform a similar decomposition of an integer number, into the highest inferior triangular number and a remainder. In the same terms, this is (i, r) = g(n) verifying that n = i * (i + 1) / 2 + r with maximal i.

What’s the way to go? What’s the fastest I can get compared to euclidean division?