giulio98/xlcost-single-prompt huggingface dataset:
# sum of all composite numbers lying in the range [ l , r ] for q queries | prefix array to precompute the sum of all composite number ; function that return number num if num is composite else return 0 ; corner cases ; this is checked so that we can skip middle five numbers in below loop ; function to precompute the sum of all composite numbers upto 100000 ; checkcomposite ( ) return the number i if i is composite else return 0 ; function to print the sum for each query ; function to prsum of all composite numbers between ; function that pre computes the sum of all composite numbers ; iterate over all queries to print the sum ; 

pref = [0] * 100001


def isComposite(n):
    if (n <= 1):
        return 0
    if (n <= 3):
        return 0
    if (n % 2 == 0 or n % 3 == 0):
        return n
    i = 5
    while (i * i <= n):
        if (n % i == 0 or n % (i + 2) == 0):
            return n
        i = i + 6
    return 0


def preCompute():
    for i in range(1, 100001):
        pref[i] = pref[i - 1] + isComposite(i)


def printSum(L, R):
    print(pref[R] - pref[L - 1])


def printSumcomposite(arr, Q):
    preCompute()
    for i in range(Q):
        printSum(arr[i][0], arr[i][1])


if __name__ == "__main__":
    Q = 2
    arr = [[10, 13], [12, 21]]
    printSumcomposite(arr, Q)

# Expected output:
22
116
# probability of getting a perfect square when a random number is chosen in a given range | python3 implementation to find the probability of getting a perfect square number ; function to return the probability of getting a perfect square number in a range ; count of perfect squares ; total numbers in range l to r ; calculating probability ; 

import math


def findProb(l, r):
    countOfPS = (math .floor(math .sqrt(r)) - math .ceil(math .sqrt(l)) + 1)
    total = r - l + 1
    prob = countOfPS / total
    return prob


if __name__ == '__main__':
    L = 16
    R = 25
    print(findProb(L, R))

# Expected output:
0.2
# find the length of factorial of a number in any given base | a optimised program to find the number of digits in a factorial in base b ; returns the number of digits present in n ! in base b since the result can be large long long is used as return type ; factorial of - ve number doesn 't exists ; base case ; use kamenetsky formula to calculate the number of digits ; 

from math import log10, floor


def findDigits(n, b):
    if (n < 0):
        return 0
    M_PI = 3.141592
    M_E = 2.7182
    if (n <= 1):
        return 1
    x = ((n * log10(n / M_E) + log10(2 * M_PI * n) / 2.0)) / (log10(b))
    return floor(x) + 1


if __name__ == '__main__':
    print(findDigits(4, 16))
    print(findDigits(5, 8))
    print(findDigits(12, 16))
    print(findDigits(19, 13))

# Expected output:
2
3
8
16
# count twin prime pairs in an array | python 3 program to count twin prime pairs in array ; a utility function to check if the number n is prime or not ; base cases ; check to skip middle five numbers in below loop ; if n is divisible by i and i + 2 then it is not prime ; a utility function that check if n1 and n2 are twin primes or not ; function to find twin prime pairs from the given array ; iterate through all pairs ; increment count if twin prime pair ; 

from math import sqrt


def isPrime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    for i in range(5, int(sqrt(n)) + 1, 6):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
    return True


def twinPrime(n1, n2):
    return (isPrime(n1) and isPrime(n2) and abs(n1 - n2) == 2)


def countTwinPairs(arr, n):
    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if (twinPrime(arr[i], arr[j])):
                count += 1
    return count


if __name__ == '__main__':
    arr = [2, 3, 5, 11]
    n = len(arr)
    print(countTwinPairs(arr, n))

# Expected output:
1
# fill the missing numbers in the array of n natural numbers such that arr [ i ] not equal to i | function to fill the position with arr [ i ] = 0 ; inserting all elements in missing [ ] set from 1 to n ; inserting unfilled positions ; removing allocated_elements ; loop for filling the positions with arr [ i ] != i ; checking for any arr [ i ] = i ; finding the suitable position in the array to swap with found i for which arr [ i ] = i ; checking if the position is present in unfilled_position ; swapping arr [ i ] & arr [ pos ] ( arr [ pos ] = pos ) ; function to print the array ; 
def printArray(arr, n):
    for i in range(1, n):
        print(arr[i], end=" ")

def solve(arr, n):
    unfilled_indices = {}
    missing = {}
    for i in range(n):
        missing[i] = 1
    for i in range(1, n):
        if (arr[i] == 0):
            unfilled_indices[i] = 1
        else:
            del missing[arr[i]]
    it2 = list(missing .keys())
    m = len(it2)
    for it in unfilled_indices:
        arr[it] = it2[m - 1]
        m -= 1
    pos = 0
    for i in range(1, n):
        if (arr[i] == i):
            pos = i
    x = 0
    if (pos != 0):
        for i in range(1, n):
            if (pos != i):
                if i in unfilled_indices:
                    x = arr[i]
                    arr[i] = pos
                    arr[pos] = x
                    break
    printArray(arr, n)


if __name__ == '__main__':
    arr = [0, 7, 4, 0, 3, 0, 5, 1]
    n = len(arr)
    solve(arr, n)

# Expected output:
7 4 6 3 2 5 1
# find kth number from sorted array formed by multiplying any two numbers in the array | function to find number of pairs ; negative and negative ; add possible pairs ; positive and positive ; add possible pairs ; negative and positive ; add possible pairs ; function to find the kth element in the list ; separate positive and negative elements ; sort the elements ; binary search ; return the required answer ; 
def check(x, pos, neg, k):
    pairs = 0
    p = len(neg) - 1
    nn = len(neg) - 1
    pp = len(pos) - 1
    for i in range(len(neg)):
        while (p >= 0 and neg[i] * neg[p] <= x):
            p -= 1
        pairs += min(nn - p, nn - i)
    p = 0
    for i in range(len(pos) - 1, -1, -1):
        while (p < len(pos) and pos[i] * pos[p] <= x):
            p += 1
        pairs += min(p, i)
    p = len(pos) - 1
    for i in range(len(neg) - 1, -1, -1):
        while (p >= 0 and neg[i] * pos[p] <= x):
            p -= 1
        pairs += pp - p
    return (pairs >= k)


def kth_element(a, n, k):
    pos, neg = [], []
    for i in range(n):
        if (a[i] >= 0):
            pos .append(a[i])
        else:
            neg .append(a[i])
    pos = sorted(pos)
    neg = sorted(neg)
    l = -10 ** 18
    ans = 0
    r = 10 ** 18
    while (l <= r):
        mid = (l + r) >> 1
        if (check(mid, pos, neg, k)):
            ans = mid
            r = mid - 1
        else:
            l = mid + 1
    return ans


a = [-4, -2, 3, 3]
k = 3
n = len(a)
print(kth_element(a, n, k))

# Expected output:
-6
# find root of a number using newton 's method | function to return the square root of a number using newtons method ; assuming the sqrt of n as n only ; to count the number of iterations ; calculate more closed x ; check for closeness ; update root ; 
def squareRoot(n, l):
    x = n
    count = 0
    while (1):
        count += 1
        root = 0.5 * (x + (n / x))
        if (abs(root - x) < l):
            break
        x = root
    return root


if __name__ == "__main__":
    n = 327
    l = 0.00001
    print(squareRoot(n, l))

# Expected output:
18.083141320025124
# goldbach 's weak conjecture for odd numbers | function to check if a number can be represent as as a sum of 3 prime ; 
def check(n):
    if n % 2 == 1 and n > 5:
        print('YES')
    else:
        print('NO')


def main():
    a = 3
    b = 7
    check(a)
    check(b)


main()

# Expected output:
NO
YES
# number of ways to reach ( x , y ) in a matrix starting from the origin | python3 implementation of the approach ; to store the factorial and factorial mod inverse of the numbers ; function to find ( a ^ m1 ) % mod ; function to find the factorial of all the numbers ; function to find the factorial modinverse of all the numbers ; function to return ncr ; function to return the number of ways to reach ( x , y ) in a matrix with the given moves starting from the origin ; 

N = 1000005
mod = (int)(1e9 + 7)
factorial = [0] * N
modinverse = [0] * N


def power(a, m1):
    if (m1 == 0):
        return 1
    elif (m1 == 1):
        return a
    elif (m1 == 2):
        return (a * a) % mod
    elif (m1 & 1):
        return (a * power(power(a, m1 // 2), 2)) % mod
    else:
        return power(power(a, m1 // 2), 2) % mod


def factorialfun():
    factorial[0] = 1
    for i in range(1, N):
        factorial[i] = (factorial[i - 1] * i) % mod


def modinversefun():
    modinverse[N - 1] = power(factorial[N - 1], mod - 2) % mod
    for i in range(N - 2, -1, -1):
        modinverse[i] = (modinverse[i + 1] * (i + 1)) % mod


def binomial(n, r):
    if (r > n):
        return 0
    a = (factorial[n] * modinverse[n - r]) % mod
    a = (a * modinverse[r]) % mod
    return a


def ways(x, y):
    factorialfun()
    modinversefun()
    if ((2 * x - y) % 3 == 0 and (2 * y - x) % 3 == 0):
        m = (2 * x - y) // 3
        n = (2 * y - x) // 3
        return binomial(n + m, n)


if __name__ == "__main__":
    x = 3
    y = 3
    print(ways(x, y))

# Expected output:
2
# find nth even length palindromic number formed using digits x and y | python3 program to find nth even palindromic number of only even length composing of 4 ' s ▁ and ▁ 5' s . ; utility function to compute n 'th palindrome number  ; calculate the length from above formula as discussed above ; calculate rank for length l ; mask to check if i 't bit   is set or not  ; if bit is set append '5' else append '4' ; 

from math import ceil, log2


def solve(n, x, y):
    length = ceil(log2(n + 2)) - 1
    rank = n - (1 << length) + 1
    left = ""
    right = ""
    for i in range(length - 1, -1, -1):
        mask = (1 << i)
        bit = (mask & rank)
        if (bit):
            left += y
            right += y
        else:
            left += x
            right += x
    right = right[::-1]
    res = left + right
    return res


if __name__ == "__main__":
    n = 23
    x = '4'
    y = '5'
    ans = solve(n, x, y)
    print(ans)

# Expected output:
54444445
# maximum of all the integers in the given level of pascal triangle | function for the binomial coefficient ; calculate value of binomial coefficient in bottom up manner ; base cases ; calculate value using previously stored values ; function to return the maximum value in the nth level of the pascal 's triangle ; 
def binomialCoeff(n, k):
    C = [[0 for i in range(k + 1)]for i in range(n + 1)]
    for i in range(n + 1):
        for j in range(min(i, k) + 1):
            if (j == 0 or j == i):
                C[i][j] = 1
            else:
                C[i][j] = C[i - 1][j - 1] + C[i - 1][j]
    return C[n][k]


def findMax(n):
    return binomialCoeff(n, n // 2)


n = 5
print(findMax(n))

# Expected output:
10
# length of the smallest sub | python 3 program to find the length of the smallest substring consisting of maximum distinct characters ; find maximum distinct characters in any string ; initialize all character 's  count with 0 ; increase the count in array if a character is found ; size of given string ; find maximum distinct characters in any string ; result ; brute force approach to find all substrings ; we have to check here both conditions together 1. substring ' s ▁ distinct ▁ characters ▁ is ▁ equal ▁ ▁ to ▁ maximum ▁ distinct ▁ characters ▁ ▁ 2 . ▁ substring ' s length should be minimum ; 

NO_OF_CHARS = 256


def max_distinct_char(str, n):
    count = [0] * NO_OF_CHARS
    for i in range(n):
        count[ord(str[i])] += 1
    max_distinct = 0
    for i in range(NO_OF_CHARS):
        if (count[i] != 0):
            max_distinct += 1
    return max_distinct


def smallesteSubstr_maxDistictChar(str):
    n = len(str)
    max_distinct = max_distinct_char(str, n)
    minl = n
    for i in range(n):
        for j in range(n):
            subs = str[i:j]
            subs_lenght = len(subs)
            sub_distinct_char = max_distinct_char(subs, subs_lenght)
            if (subs_lenght < minl and max_distinct == sub_distinct_char):
                minl = subs_lenght
    return minl


if __name__ == "__main__":
    str = "AABBBCBB"
    l = smallesteSubstr_maxDistictChar(str)
    print(
        "The length of the smallest substring",
        "consisting of maximum distinct",
        "characters :",
        l)

# Expected output:
The length of the smallest substring consisting of maximum distinct characters : 5
# find two co | python3 implementation of the approach ; function to find the required numbers ; gcd of the given numbers ; printing the required numbers ; 

from math import gcd


def findNumbers(a, b):
    __gcd = gcd(a, b)
    print((a // __gcd), (b // __gcd))


if __name__ == "__main__":
    a = 12
    b = 16
    findNumbers(a, b)

# Expected output:
3 4
# find the remaining balance after the transaction | function to find the balance ; check if the transaction can be successful or not ; transaction is successful ; transaction is unsuccessful ; 
def findBalance(x, bal):
    if (x % 10 == 0 and (x + 1.50) <= bal):
        print(round(bal - x - 1.50, 2))
    else:
        print(round(bal, 2))


x = 50
bal = 100.50
findBalance(x, bal)

# Expected output:
49.0
# count number of pairs in array having sum divisible by k | set 2 | python program to count pairs whose sum divisible by 'k ; program to count pairs whose sum divisible by ' k ' ; create a frequency array to count occurrences of all remainders when divided by k ; to store count of pairs . ; traverse the array , compute the remainder and add k - remainder value hash count to ans ; count number of ( a [ i ] , ( k - rem ) % k ) pairs ; increment count of remainder in hash map ; 
def countKdivPairs(A, n, K):
    freq = [0 for i in range(K)]
    ans = 0
    for i in range(n):
        rem = A[i] % K
        ans += freq[(K - rem) % K]
        freq[rem] += 1

    return ans


if __name__ == '__main__':
    A = [2, 2, 1, 7, 5, 3]
    n = len(A)
    K = 4
    print(countKdivPairs(A, n, K))

# Expected output:
5
# minimum number of bottles visible when a bottle can be enclosed inside another bottle | python3 code for the above approach ; 
def min_visible_bottles(arr, n):
    m = dict()
    ans = 0
    for i in range(n):
        m[arr[i]] = m .get(arr[i], 0) + 1
        ans = max(ans, m[arr[i]])
    print("Minimum number of", "Visible Bottles are: ", ans)


n = 8
arr = [1, 1, 2, 3, 4, 5, 5, 4]
min_visible_bottles(arr, n)

# Expected output:
Minimum number of Visible Bottles are:  2
# find the final sequence of the array after performing given operations | function that generates the array b [ ] when n is even ; fill the first half of the final array with reversed sequence ; fill the second half ; function that generates the array b [ ] when n is odd ; fill the first half of the final array with reversed sequence ; fill the second half ; function to find the final array b [ ] after n operations of given type ; create the array b ; if the array size is even ; print the final array elements ; 
def solveEven(n, arr, b):
    left = n - 1
    for i in range((n // 2)):
        b[i] = arr[left]
        left = left - 2
        if (left < 0):
            break
    right = 0
    for i in range(n // 2, n, 1):
        b[i] = arr[right]
        right = right + 2
        if (right > n - 2):
            break


def solveOdd(n, arr, b):
    left = n - 1
    for i in range(n // 2 + 1):
        b[i] = arr[left]
        left = left - 2
        if (left < 0):
            break
    right = 1
    for i in range(n // 2 + 1, n, 1):
        b[i] = arr[right]
        right = right + 2
        if (right > n - 2):
            break


def solve(n, arr):
    b = [0 for i in range(n)]
    if (n % 2 == 0):
        solveEven(n, arr, b)
    else:
        solveOdd(n, arr, b)
    for i in range(n):
        print(b[i], end=" ")


if __name__ == '__main__':
    arr = [1, 2, 3, 4]
    n = len(arr)
    solve(n, arr)

# Expected output:
4 2 1 3
# find the sum of the first half and second half elements of an array | function to find the sum of the first half elements and second half elements of an array ; add elements in first half sum ; add elements in the second half sum ; 
def sum_of_elements(arr, n):
    sumfirst = 0
    sumsecond = 0
    for i in range(n):
        if (i < n // 2):
            sumfirst += arr[i]
        else:
            sumsecond += arr[i]
    print("Sum of first half elements is", sumfirst, end="")
    print("Sum of second half elements is", sumsecond, end="")


arr = [20, 30, 60, 10, 25, 15, 40]
n = len(arr)
sum_of_elements(arr, n)

# Expected output:
Sum of first half elements is 110Sum of second half elements is 90
# sequence with sum k and minimum sum of absolute differences between consecutive elements | function to return the minimized sum ; if k is divisible by n then the answer will be 0 ; else the answer will be 1 ; 
def minimum_sum(n, k):
    if (k % n == 0):
        return 0
    return 1


n = 3
k = 56
print(minimum_sum(n, k))

# Expected output:
1
# print first n terms of lower wythoff sequence | python3 implementation of the approach ; function to print the first n terms of the lower wythoff sequence ; calculate value of phi ; find the numbers ; a ( n ) = floor ( n * phi ) ; print the nth numbers ; 

from math import sqrt, floor


def lowerWythoff(n):
    phi = (1 + sqrt(5)) / 2
    for i in range(1, n + 1):
        ans = floor(i * phi)
        print(ans, end="")
        if (i != n):
            print(", ", end="")


if __name__ == "__main__":
    n = 5
    lowerWythoff(n)

# Expected output:
1, 3, 4, 6, 8
# count of quadruplets from range [ l , r ] having gcd equal to k | python 3 implementation of the approach ; function to return the count of quadruplets having gcd = k ; to store the required count ; check every quadruplet pair whether its gcd is k ; return the required count ; 

from math import gcd


def countQuadruplets(l, r, k):
    count = 0
    for u in range(l, r + 1, 1):
        for v in range(l, r + 1, 1):
            for w in range(l, r + 1, 1):
                for x in range(l, r + 1, 1):
                    if (gcd(gcd(u, v), gcd(w, x)) == k):
                        count += 1
    return count


if __name__ == '__main__':
    l = 1
    r = 10
    k = 2
    print(countQuadruplets(l, r, k))

# Expected output:
607
# find an index such that difference between product of elements before and after it is minimum | function to return the index i such that the absolute difference between product of elements up to that index and the product of rest of the elements of the array is minimum ; to store the required index ; prefix product array ; compute the product array ; iterate the product array to find the index ; 
def findIndex(a, n):
    res, min_diff = None, float('inf')
    prod = [None] * n
    prod[0] = a[0]
    for i in range(1, n):
        prod[i] = prod[i - 1] * a[i]
    for i in range(0, n - 1):
        curr_diff = abs((prod[n - 1] // prod[i]) - prod[i])
        if curr_diff < min_diff:
            min_diff = curr_diff
            res = i
    return res


if __name__ == "__main__":
    arr = [3, 2, 5, 7, 2, 9]
    N = len(arr)
    print(findIndex(arr, N))

# Expected output:
2
# print all numbers whose set of prime factors is a subset of the set of the prime factors of x | python3 program to implement the above approach ; function to print all the numbers ; iterate for every element in the array ; find the gcd ; iterate till gcd is 1 of number and x ; divide the number by gcd ; find the new gcdg ; if the number is 1 at the end then print the number ; if no numbers have been there ; 

from math import gcd


def printNumbers(a, n, x):
    flag = False
    for i in range(n):
        num = a[i]
        g = gcd(num, x)
        while (g != 1):
            num //= g
            g = gcd(num, x)
        if (num == 1):
            flag = True
            print(a[i], end=" ")
    if (not flag):
        print("There are no such numbers")


if __name__ == "__main__":
    x = 60
    a = [2, 5, 10, 7, 17]
    n = len(a)
    printNumbers(a, n, x)

# Expected output:
2 5 10
# find the final radiations of each radiated stations | function to print the final radiations ; function to create the array of the resultant radiations ; resultant radiations ; declaring index counter for left and right radiation ; effective radiation for left and right case ; radiation for i - th station ; radiation increment for left stations ; radiation increment for right stations ; print the resultant radiation for each of the stations ; 
def printf(rStation, n):
    for i in range(1, n + 1, 1):
        print(rStation[i], end=" ")
    print("",  end="")


def radiated_Station(station, n):
    rStation = [0 for i in range(n + 1)]
    for i in range(1, n + 1):
        li = i - 1
        ri = i + 1
        lRad = station[i] - 1
        rRad = station[i] - 1
        rStation[i] += station[i]
        while (li >= 1 and lRad >= 1):
            rStation[li] += lRad
            lRad -= 1
            li -= 1
        while (ri <= n and rRad >= 1):
            rStation[ri] += rRad
            rRad -= 1
            ri += 1
    printf(rStation, n)


if __name__ == '__main__':
    station = [0, 7, 9, 12, 2, 5]
    n = len(station) - 1
    radiated_Station(station, n)

# Expected output:
26 28 29 28 25
# program to find the maximum difference between the index of any two different numbers | function to return the maximum difference ; iteratively check from back ; different numbers ; iteratively check from the beginning ; different numbers ; 
def findMaximumDiff(a, n):
    ind1 = 0
    for i in range(n - 1, -1, -1):
        if (a[0] != a[i]):
            ind1 = i
            break
    ind2 = 0
    for i in range(n - 1):
        if (a[n - 1] != a[i]):
            ind2 = (n - 1 - i)
            break
    return max(ind1, ind2)


a = [1, 2, 3, 2, 3]
n = len(a)
print(findMaximumDiff(a, n))

# Expected output:
4
# sum of the series kn + ( k ( n | function to return sum ; 
def sum(k, n):
    sum = (pow(k, n + 1) - pow(k - 1, n + 1))
    return sum


n = 3
K = 3
print(sum(K, n))

# Expected output:
65
# Check whether factorial of N is divisible by sum of first N natural numbers | Function to check whether a number is prime or not . ; Count variable to store the number of factors of 'num ; Counting the number of factors ; If number is prime return true ; Function to check for divisibility ; if ' n ' equals 1 then divisibility is possible ; Else check whether ' n + 1' is prime or not ; If ' n + 1' is prime then ' n ! ' is not divisible by 'n*(n+1)/2 ; else divisibility occurs ; Test for n = 3 ; Test for n = 4
def is_prime(num):
    count = 0
    for i in range(1, num + 1):

        if i * i > num:
            break

        if ((num) % i == 0):

            if (i * i != (num)):
                count += 2
            else:
                count += 1
    if (count == 2):
        return True
    else:
        return False


def is_divisible(n):
    if (n == 1):
        return "YES"
    else:
        if (is_prime(n + 1)):
            return "NO"
        else:
            return "YES"


n = 3

print(is_divisible(n))
n = 4

print(is_divisible(n))

# Expected output:
YES
NO