nt.number theory – On numbers that are sums of reciprocals of integers

Suppose $r$ is a positive real number. When is there a set $I$ (finite or infinite) of positive integers such that $sumlimits_{iin I} i^{-1} =r$? In other words, which positive real numbers can be realized as sums of reciprocals of integers, without multiplicity? I think there are uncountably-many sets $I$ for which the sum does converge, and of course divergence of the harmonic series means we can add elements to $I$ to increase the sum without bound, so I don’t see any obvious ways to rule out any significant ranges of $r$. On the other hand I’d be rather surprised if the answer was “always.”

solution verification – How to proof this statement. “There are not odd integers x,y,z according to $(x-z)^2$ + $(y-z)^2$ = $(x+y)^2$.”

I did try to proof this by contradiction(I guess it works). So I suppose this statement is false but I have confused about the meaning of it.

If this statment is false it means “There are odd integers x,y,z according to $(x-z)^2$ + $(y-z)^2$ = $(x+y)^2$.” or “There are odd integers x,y,z according to $(x-z)^2$ + $(y-z)^2$ $neq$ $(x+y)^2$.” or…..

Is proof by contradiction a good method? and Could you help me how to do next from the statement that suppose to be false?

Thank you very much.

algorithms – Is there a way to determine whether a list of integers can be a prefix function?

Say you had

(0,0,0,1,2,3,4,5,6,7,8,9,10)

or

(0,1,0,1,0,1,2,3,0,1,0,0,1)

Could you use, for example, the KMP algorithm to deduce the validity of the above lists as prefix functions? I know there is a way to find whether a substring exists in a string using KMP, but is there a way to do it the other way around, starting at the apparent prefix function and ascertaining that it is indeed a possible prefix function, without knowing the string/substring itself at the start?

how to solve a quadratic diophanic equation on integers and obtain various results

This quadratic di equation has more results, as it came to them.

I can only think of this

FindInstance((4 p + 3 q - 2) (p - 1) == (6 p + 2 q) q, {p,  q}, Integers)

ac.commutative algebra – Characterization of algebraic integers providing a prime ideal

Let $alpha$ be an algebraic integer and let $mathcal{O}_{mathbb{Q}(alpha)}$ be the ring of integers of $mathbb{Q}(alpha)$.

Question: How to characterize the algebraic integers $alpha$ such that $alpha mathcal{O}_{mathbb{Q}(alpha)}$ is a prime ideal of $mathcal{O}_{mathbb{Q}(alpha)}$?

Example: if $alpha in mathbb{Z}$, then $mathcal{O}_{mathbb{Q}(alpha)} = mathbb{Z}$, so that $alpha mathcal{O}_{mathbb{Q}(alpha)}$ is a prime ideal iff $alpha$ is a prime number (up to a sign).

pr.probability – Asymptotic inversion formula in additive number theory (sums of two sets of positive integers)

Let $S$ be an infinite set of positive integers, and $T=S+S={x+y, mbox{ with } x,yin S}$.We definte the following functions:

  • $N_S(z)$ is asymptotic continuous version of the function counting the number of elements in $S$ less or equal to $z$.
  • $N’_S(z)$, the derivative of $N_S(z)$, is the “probability” for $z$
    (an integer) to belong to $S$
  • $r(z)$ is the asymptotic continuous version of the function counting
    the number of solutions $x+y leq z$ with $x,yin S$.
  • $r'(z)$ is the derivative of $r(z)$.

We will work with
$$N_S(z) sim frac{az^b}{(log z)^c}.$$

Here $frac{1}{2}< b leq 1$ and $a>0, cgeq 0$. The case $b=1, c=0$ should be excluded. This covers a vast array of sets: sums of primes, sums of super-primes etc. The following is a known result (see here):

$$r(z) sim frac{a^2 z^{2b}}{(log z)^{2c}}cdot frac{Gamma^2(b+1)}{Gamma(2b+1)}$$
$$r'(z) sim frac{a^2 z^{2b-1}}{(log z)^{2c}}cdot frac{Gamma^2(b+1)}{Gamma(2b)}$$

More generally (see here):

$$r(z) sim zint_0^{1} N_S(z(1-v))N’_S(zv) dv.$$
$$r'(z) sim zint_0^{1} N’_S(z(1-v))N’_S(zv) dv .$$

Since $b>frac{1}{2}$, we have $r'(z) rightarrow infty$ as $zrightarrow infty$. This guarantees (it’s a conjecture) that barring congruence restrictions, $T = S + S$ contains all the positive integers except a finite number of them. The inversion formula is as follows:

Inversion formula

$$N_T(z) = z-w(z), mbox{ with } w(z) sim int_0^z expBig(-frac{1}{2} r'(u)Big)du.$$

Since $r’$ is a function of $N’$ and thus, a function of $N$, we have a formula linking $N_T$ to $N_S$. So if you know $N_T$, by inversion (it involves solving an integral equation, though we are only interested in the asymptotic value of the solution) technically, you can retrieve $N_S$, assuming the solution is unique (chances are that the solution is far from unique.)

Note that $w(z)$ represents the number of positive integers, less or equal to $z$, that do not belong to $T=S+S$. These integers are called exceptions. We also have $w(infty) = C_S$: this constant depends on $S$, but it is finite and it represents an estimate of the total number of exceptions. I tried to assess the validity of the inversion formula using some test sets $S$, and empirical evidence suggests that it is correct. Essentially, it is based on the following simple probabilistic argument. Let $u(z)$ be the probability that $z$ (an integer) is an exception. Then, if $r'(z)rightarrowinfty$ as $zrightarrowinfty$ and $S$ is free of congruence restrictions and other sources of non-randomness, then
$$u(z) sim expBig(-frac{1}{2}r'(z)Big).$$

Testing the formula on an example

I created 100 test sets $S$, with $a=1, b=frac{2}{3}, c=0$, as follows: an integer $k$ belongs to $S$ if and only if $U_k<N’_S(k)$, where the $U_k$‘s are independent uniform deviates on $(0, 1)$. I computed various statistics, but I will mention only one here. The theoretical value for $w(infty)$ is
$$w(infty) approx int_0^infty expBig(-frac{lambda}{2}u^{1/3}Big)du approx 63.76, mbox{ with } lambda = frac{Gamma^2(frac{5}{3})}{Gamma(frac{4}{3})}.$$

Note that the above integral can be computed explicitly. I then conjectured the value $w(infty)$ for each of the 100 test sets. It ranged from $13$ to $199$, with an average value of $65.88$. Again, $w(infty)$ is an estimate of the number of exceptions, that is, positive integers that can not be represented as $x+y$ with $x, y in S$. So the approximate theoretical value is in agreement with the average value inferred from my experiment.

My question

Is this inversion formula well known? Can it be of any practical use? Can it be further refined, maybe generalized to sums of three sets or made more accurate with bounds on the error term?

How many pairs of integers x,y exists satisfy a equation ax + by = d

I am solving a programming problem where constraints are high ( 0<=a,b,d<=1e9). How can i count all pairs (x,y) given a,b and d.

python – Convert Roman Numerals to integers

This is my first post, so I welcome any etiquette corrections.

I know there are many questions about this exercise, but I am mostly interested in comments regarding my specific attempt.

A fun beginner’s problem in programming is to write a program which will convert Roman Numeral input to Arabic integers. I, a beginner, have written such a program in Python without using any other sources (I came up with it all on my own). It now works, and I would welcome any comments or considerations, especially with regards to the following: general best practice, whether the input verification can be made cleaner, if there is a nicer way than using a dictionary to match the characters and values, efficiency of the part which calculates the totals, etc.

Please consider the following: there are differing opinions about what constitutes ‘proper’ Roman Numerals (for example, ‘IIII’ is odd but known to exist in ancient writings, and ‘VIV’ is a stupid but understandable way to write ‘9’), so my program will treat any valid string as acceptable and attempt to parse it. Please let me know if I should add comments to the code. Here it is:

import re

bad = 1                                                                                     

while bad == 1:
    roman = input('Enter a Roman Numeral: ')
    test = re.findall('(^IVXLCDM)+', roman)                                                 
    lengthtracker = 0                                                                       
    for item in test:
        length = len(item)
        lengthtracker = lengthtracker + length                                              
        if length != 0:
            print('Roman Numerals may contain only the characters I, V, X, L, C, D, M')
            break
        else:
            continue
    if lengthtracker == 0:
        bad = 0                                                                             

print('Roman Numeral verified!')                                                            

ref = dict()                                                                                
ref('I') = 1
ref('V') = 5
ref('X') = 10
ref('L') = 50
ref('C') = 100
ref('D') = 500
ref('M') = 1000

n = len(roman)
m = 0
total = 0
negtotal = 0
tenttotal = 0
while m < n-1:
    if ref(roman(m)) == ref(roman(m+1)):
        tenttotal = tenttotal + ref(roman(m))
    elif ref(roman(m)) > ref(roman(m+1)):
        total = total + tenttotal + ref(roman(m))
        tenttotal = 0
    else:
        negtotal = negtotal + tenttotal + ref(roman(m))
        tenttotal = 0
    print(total, negtotal, tenttotal)
    m = m + 1

total = total + tenttotal + ref(roman(m)) - negtotal
    

print('It equals:', total)

python – anyone have solution for this error ” TypeError: byte indices must be integers or slices, not list “

i taking out the id number from my database so that i can fetch the data(blob) to download it. im facing some error with bytes indice and the ” TypeError: a bytes-like object is required, not ‘int’ “. i had been working on this for so long.

@app.route("/search", methods=('GET','POST'))
def search():

    if request.method == "POST":

        if not request.form.get("search"):

            return error("error")

        conn= sqlite3.connect("YTD2.db")
        cursor = conn.cursor()
        c = cursor.execute("SELECT * FROM my_table")

        id = db.execute("SELECT id FROM my_table WHERE name=:name", 
                        name=request.form.get("search"))
        # print(data)
    
        for x in c.fetchall():
            data_v=x(1)(id)
            break
        
        conn.commit()
        cursor.close()
        conn.close()

        # print(c)    
        return send_file(BytesIO(data_v), attachment_filename='download.pdf', as_attachment=True)
    
    return redirect("home.html")

here is the code
anyone else have some good algorithm to flask blob from database and store as PDF, i had been working on this using flask_wtf

programming challenge – C++, sort integers using knowledge of entire vector

I am solving the “Sort” problem on Kattis.

Mirko is a great code breaker. He knows any cipher in the world can be broken by frequency analysis. He has completely the wrong idea what frequency analysis is, however.
He intercepted an enemy message. The message consists of N
numbers, smaller than or equal to C.
Mirko belives freqency analysis consists of sorting this sequence so that more frequent numbers appear before less frequent ones.
Formally, the sequence must be sorted so that given any two numbers X
and Y, X appears before Y if the number of times X appears in the original sequence is larger than the number of time Y does. If the number of appearances is equal, the number whose value appears sooner in the input should appear sooner in the sorted sequence.
Help Mirko by creating a “frequency sorter”.
Input
First line of input contains two integers, N (1≤N≤1000), the length of the message, and C (1≤C≤1000000000), the number from the task description above.
The next line contains N positive integers smaller than or equal to C, the message itself.

Basically, the problem is as follows. Let xs be a nonempty vector of positive integers. There are only few integers in this vector, but they have a big range. (The maximum value c is given in the problem, but my code does not use the information.) Sort the integers according to the following criteria.

  1. For any two elements x and y of xs, if x occurs more often than y, then x appears first; if y appears more often, y appears first.
  2. If x and y appear equally often, then x occurs first if the very first occurrence of x is earlier than that of y.

I use a comparison sort (provided by the C++ runtime) with a smart comparator. This comparator knows the frequency and the index of the first appearance of every element. This information is not inherent to the integers. Rather, it depends entirely on their location within the vector. This contextual information is generated when a comparator is created for a given vector. Upon application on elements x and y, it returns true if x must appear before y.

I have used custom comparators before, but never have I used anything that contains state. In the disassembly with -Os I see many copy and move constructors called under sort(vector<unsigned> &). The code passes all tests, and it’s not slow.

But I wonder why the disassembly reveals so many copy and move calls, and whether this pattern of using heavy comparators is discouraged in C++. If this looks like a known pattern, I want to know its name. I appreciate general comments and insights.

#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <iostream>

typedef std::vector<unsigned> vector;

/// Comparison based on knowledge of the entire vector
struct compare {
    std::multiset<unsigned> bag;
    std::map<unsigned, size_t> indices;

    /// Extract frequency and initial index of every element.
    explicit compare(vector const &xs) {
        for (size_t i = 0u; i < xs.size(); ++i) {
            unsigned const x = xs(i);
            bag.insert(x);
            if (!indices.count(x)) {
                indices(x) = i;
            }
        }
    }

    /// True if `x` must go before `y`.
    ((nodiscard)) bool operator()(unsigned x, unsigned y) const {
        return bag.count(x) > bag.count(y)
               || (bag.count(x) == bag.count(y) && indices.at(x) < indices.at(y));
    }
};

static void sort(vector &v) {
    compare c(v);
    std::sort(v.begin(), v.end(), c);
}

int main() {
    vector v;
    {
        // Get `n` unsigned integers from console.
        // Unused: `c` (upper bound for integers)
        unsigned n, c;
        std::cin >> n >> c;
        v.reserve(n);
        while (n--) {
            unsigned x;
            std::cin >> x;
            v.push_back(x);
        }
    }
    // Sort according to the problem description
    sort(v);
    // Print all
    for (unsigned const x : v) {
        std::cout << x << ' ';
    }
    return 0;
}