giulio98/xlcost-single-prompt huggingface dataset:
# n 'th palindrome of k digits | python3 program of finding nth palindrome of k digit ; determine the first half digits ; print the first half digits of palindrome ; if k is odd , truncate the last digit ; print the last half digits of palindrome ; 
def nthPalindrome(n, k):
    if (k & 1):
        temp = k // 2
    else:
        temp = k // 2 - 1
    palindrome = 10 ** temp
    palindrome = palindrome + n - 1
    print(palindrome, end="")
    if (k & 1):
        palindrome = palindrome // 10
    while (palindrome):
        print(palindrome % 10, end="")
        palindrome = palindrome // 10


if __name__ == '__main__':
    n = 6
    k = 5
    print(n, "th palindrome of", k, " digit = ", end=" ")
    nthPalindrome(n, k)
    print()
    n = 10
    k = 6
    print(n, "th palindrome of", k, "digit = ", end=" ")
    nthPalindrome(n, k)

# Expected output:
6 th palindrome of 5  digit =  10501
10 th palindrome of 6 digit =  109901
# maximum value in an array after m range increment operations | python3 progrma of simple approach to find maximum value after m range increments . ; function to find the maximum element after m operations ; start performing m operations ; store lower and upper index i . e . range ; add ' k [ i ] ' value at this operation to whole range ; find maximum value after all operations and return ; 

import sys


def findMax(n, a, b, k, m):
    arr = [0] * n
    for i in range(m):
        lowerbound = a[i]
        upperbound = b[i]
        for j in range(lowerbound, upperbound + 1):
            arr[j] += k[i]
            res = -sys .maxsize - 1
            for i in range(n):
                res = max(res, arr[i])
                return res


if __name__ == "__main__":
    n = 5
    a = [0, 1, 2]
    b = [1, 4, 3]
    k = [100, 100, 100]
    m = len(a)
    print("Maximum value after 'm' operations is ", findMax(n, a, b, k, m))

# Expected output:
Maximum value after 'm' operations is  100
# Summation of GCD of all the pairs up to N | Python approach of finding sum of GCD of all pairs ; phi [ i ] stores euler totient function for i result [ j ] stores result for value j ; Precomputation of phi [ ] numbers . Refer below link for details : https : goo . gl / LUqdtY ; Refer https : goo . gl / LUqdtY ; Precomputes result for all numbers till MAX ; Precompute all phi value ; Iterate throght all the divisors of i . ; Add summation of previous calculated sum ; Function to calculate sum of all the GCD pairs

MAX = 100001
phi = [0] * MAX
result = [0] * MAX


def computeTotient():
    phi[1] = 1
    for i in range(2, MAX):
        if not phi[i]:
            phi[i] = i - 1
            for j in range(i << 1, MAX, i):
                if not phi[j]:
                    phi[j] = j
                phi[j] = ((phi[j] // i) * (i - 1))


def sumOfGcdPairs():
    computeTotient()
    for i in range(MAX):
        for j in range(2, MAX):
            if i * j >= MAX:
                break
            result[i * j] += i * phi[j]
    for i in range(2, MAX):
        result[i] += result[i - 1]


sumOfGcdPairs()
N = 4
print("Summation of", N, "=", result[N])
N = 12
print("Summation of", N, "=", result[N])
N = 5000
print("Summation of", N, "=", result[N])

# Expected output:
Summation of 4 = 7
Summation of 12 = 105
Summation of 5000 = 61567426
# find coordinates of the triangle given midpoint of each side | python3 program to find coordinate of the triangle given midpoint of each side ; return after solving the equations and finding the vertices coordinate . ; finding sum of all three coordinate . ; solving the equation . ; finds vertices of a triangles from given middle vertices . ; find x coordinates of vertices . ; find y coordinates of vertices . ; output the solution . ; 

N = 3


def solve(v):
    res = []
    all3 = v[0] + v[1] + v[2]
    res .append(all3 - v[1] * 2)
    res .append(all3 - v[2] * 2)
    res .append(all3 - v[0] * 2)
    return res


def findVertex(xmid, ymid):
    V1 = solve(xmid)
    V2 = solve(ymid)
    for i in range(0, 3):
        print(V1[i], end=" ")
        print(V2[i])


if __name__ == '__main__':
    xmid = [5, 4, 5]
    ymid = [3, 4, 5]
    findVertex(xmid, ymid)

# Expected output:
6 4
4 2
4 6
# n | return the n - th number in the sorted list of multiples of two numbers . ; generating first n multiple of a . ; sorting the sequence . ; generating and storing first n multiple of b and storing if not present in the sequence . ; if not present in the sequence ; storing in the sequence . ; 
def nthElement(a, b, n):
    seq = []
    for i in range(1, n + 1):
        seq .append(a * i)
    seq .sort()
    i = 1
    k = n
    while (i <= n and k > 0):
        try:
            z = seq .index(b * i)
        except ValueError:
            seq .append(b * i)
            seq .sort()
            k -= 1
        i += 1
    return seq[n - 1]


a = 3
b = 5
n = 5
print(nthElement(a, b, n))

# Expected output:
10
# count pairs of natural numbers with gcd equal to given number | return the gcd of two numbers . ; return the count of pairs having gcd equal to g . ; setting the value of l , r . ; for each possible pair check if gcd is 1. ; 
def gcd(a, b):
    return gcd(b, a % b)if b > 0 else a


def countGCD(L, R, g):
    L = (L + g - 1) // g
    R = R // g
    ans = 0
    for i in range(L, R + 1):
        for j in range(L, R + 1):
            if (gcd(i, j) == 1):
                ans = ans + 1
    return ans


L = 1
R = 11
g = 5
print(countGCD(L, R, g))

# Expected output:
3
# last non | initialize values of last non - zero digit of numbers from 0 to 9 ; check whether tens ( or second last ) digit is odd or even if n = 375 , so n / 10 = 37 and ( n / 10 ) % 10 = 7 applying formula for even and odd cases . ; 

dig = [1, 1, 2, 6, 4, 2, 2, 4, 2, 8]


def lastNon0Digit(n):
    if (n < 10):
        return dig[n]
    if (((n // 10) % 10) % 2 == 0):
        return (6 * lastNon0Digit(n // 5) * dig[n % 10]) % 10
    else:
        return (4 * lastNon0Digit(n // 5) * dig[n % 10]) % 10
    return 0


n = 14
print(lastNon0Digit(n))

# Expected output:
2
# find the first natural number whose factorial is divisible by x | gcd function to compute the greatest divisor among a and b ; returns first number whose factorial divides x . ; i = 1 result ; remove common factors ; we found first i . ; 
def gcd(a, b):
    if ((a % b) == 0):
        return b
    return gcd(b, a % b)


def firstFactorialDivisibleNumber(x):
    new_x = x
    for i in range(1, x):
        new_x /= gcd(i, new_x)
        if (new_x == 1):
            break
    return i


def main():
    x = 16
    print(firstFactorialDivisibleNumber(x))


if __name__ == '__main__':
    main()

# Expected output:
6
# find the highest occurring digit in prime numbers in a range | sieve of eratosthenes ; returns maximum occurring digits in primes from l to r . ; finding the prime number up to r . ; initialise frequency of all digit to 0. ; for all number between l to r , check if prime or not . if prime , incrementing the frequency of digits present in the prime number . ; p = i if i is prime ; finding digit with highest frequency . ; 
def sieve(prime, n):
    p = 2
    while p * p <= n:
        if (prime[p] == False):
            for i in range(p * 2, n, p):
                prime[i] = True

        p += 1


def maxDigitInPrimes(L, R):

    prime = [0] * (R + 1)
    sieve(prime, R)
    freq = [0] * 10
    for i in range(L, R + 1):
        if (not prime[i]):
            p = i  # If i is prime
            while (p):
                freq[p % 10] += 1
                p //= 10
    max = freq[0]
    ans = 0
    for j in range(1, 10):
        if (max <= freq[j]):
            max = freq[j]
            ans = j
    if max == 0:
        return -1
    return ans


if __name__ == "__main__":
    L = 1
    R = 20
    print(maxDigitInPrimes(L, R))

# Expected output:
1
# common divisors of two numbers | python implementation of program ; function to calculate gcd of two numbers ; function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; find gcd of a , b ; count divisors of n ; if i is a factor of n ; check if divisors are equal ; 

from math import sqrt


def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)


def commDiv(a, b):
    n = gcd(a, b)
    result = 0
    for i in range(1, int(sqrt(n)) + 1):
        if n % i == 0:
            if n / i == i:
                result += 1
            else:
                result += 2
    return result


if __name__ == "__main__":
    a = 12
    b = 24
    print(commDiv(a, b))

# Expected output:
6
# count ways to spell a number with repeated digits | function to calculate all possible spells of a number with repeated digits num -- > string which is favourite number ; final count of total possible spells ; iterate through complete number ; count contiguous frequency of particular digit num [ i ] ; compute 2 ^ ( count - 1 ) and multiply with result ; 
def spellsCount(num):
    n = len(num)
    result = 1
    i = 0
    while (i < n):
        count = 1
        while (i < n - 1 and num[i + 1] == num[i]):
            count += 1
            i += 1
        result = result * int(pow(2, count - 1))
        i += 1
    return result


num = "11112"
print(spellsCount(num))

# Expected output:
8
# happy number | utility method to return sum of square of digit of n ; method return true if n is happy number ; initialize slow and fast by n ; move slow number by one iteration ; move fast number by two iteration ; if both number meet at 1 , then return true ; 
def numSquareSum(n):
    squareSum = 0
    while (n):
        squareSum += (n % 10) * (n % 10)
        n = int(n / 10)
    return squareSum


def isHappynumber(n):
    slow = n
    fast = n
    while (True):
        slow = numSquareSum(slow)
        fast = numSquareSum(numSquareSum(fast))
        if (slow != fast):
            continue
        else:
            break
    return (slow == 1)


n = 13
if (isHappynumber(n)):
    print(n, "is a Happy number")
else:
    print(n, "is not a Happy number")

# Expected output:
13 is a Happy number
# count divisors of factorial | allprimes [ ] stores all prime numbers less than or equal to n . ; fills above vector allprimes [ ] for a given n ; create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . a value in prime [ i ] will finally be false if i is not a prime , else true . ; loop to update prime [ ] ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; store primes in the vector allprimes ; function to find all result of factorial number ; initialize result ; find exponents of all primes which divides n and less than n ; current divisor ; find the highest power ( stored in exp ) ' ▁ ▁ of ▁ allprimes [ i ] ▁ that ▁ divides ▁ n ▁ using ▁ ▁ legendre ' s formula . ; multiply exponents of all primes less than n ; return total divisors ; 

allPrimes = []


def sieve(n):
    prime = [True] * (n + 1)
    p = 2
    while (p * p <= n):
        if (prime[p]):
            i = p * 2
            while (i <= n):
                prime[i] = False
                i += p
        p += 1
    for p in range(2, n + 1):
        if (prime[p]):
            allPrimes .append(p)


def factorialDivisors(n):
    result = 1
    for i in range(len(allPrimes)):
        p = allPrimes[i]
        exp = 0
        while (p <= n):
            exp = exp + int(n / p)
            p = p * allPrimes[i]
        result = result * (exp + 1)
    return result


print(factorialDivisors(6))

# Expected output:
1
# non fibonacci numbers | returns n 'th non-fibonacci number ; curr is to keep track of current fibonacci number , prev is previous , prevprev is previous of previous . ; while count of non - fibonacci numbers doesn 't become  negative or zero ; simple fibonacci number logic ; ( curr - prev - 1 ) is count of non - fibonacci numbers between curr and prev . ; n might be negative now . make sure it becomes positive by removing last added gap . ; now add the positive n to previous fibonacci number to find the n 'th non-fibonacci. ; 
def nonFibonacci(n):
    prevPrev = 1
    prev = 2
    curr = 3
    while n > 0:
        prevPrev = prev
        prev = curr
        curr = prevPrev + prev
        n = n - (curr - prev - 1)
    n = n + (curr - prev - 1)
    return prev + n


print(nonFibonacci(5))

# Expected output:
10
# stein 's algorithm for finding gcd | function to implement stein 's algorithm ; gcd ( 0 , b ) == b ; gcd ( a , 0 ) == a , gcd ( 0 , 0 ) == 0 ; finding k , where k is the greatest power of 2 that divides both a and b . ; dividing a by 2 until a becomes odd ; from here on , ' a ' is always odd . ; if b is even , remove all factor of 2 in b ; now a and b are both odd . swap if necessary so a <= b , then set b = b - a ( which is even ) . ; restore common factors of 2 ; 
def gcd(a, b):
    if (a == 0):
        return b
    if (b == 0):
        return a
    k = 0
    while (((a | b) & 1) == 0):
        a = a >> 1
        b = b >> 1
        k = k + 1
    while ((a & 1) == 0):
        a = a >> 1
    while (b != 0):
        while ((b & 1) == 0):
            b = b >> 1
        if (a > b):
            temp = a
            a = b
            b = temp
        b = (b - a)
    return (a << k)


a = 34
b = 17
print("Gcd of given numbers is ", gcd(a, b))

# Expected output:
Gcd of given numbers is  17
# print all n | n -- > value of input out -- > output array index -- > index of next digit to be filled in output array evensum , oddsum -- > sum of even and odd digits so far ; base case ; if number becomes n - digit ; if absolute difference between sum of even and odd digits is 1 , print the number ; if current index is odd , then add it to odd sum and recurse ; else : else add to even sum and recurse ; this is mainly a wrapper over findndigitnumsutil . it explicitly handles leading digit and calls findndigitnumsutil ( ) for remaining indexes . ; output array to store n - digit numbers ; initialize number index considered so far ; initialize even and odd sums ; explicitly handle first digit and call recursive function findndigitnumsutil for remaining indexes . note that the first digit is considered to be present in even position . ; 
def findNDigitNumsUtil(n, out, index, evenSum, oddSum):
    if (index > n):
        return
    if (index == n):
        if (abs(evenSum - oddSum) == 1):
            out[index] = ''
            out = ''.join(out)
            print(out)
        return
    if (index & 1):
        for i in range(10):
            out[index] = chr(i + ord('0'))
            findNDigitNumsUtil(n, out, index + 1, evenSum, oddSum + i)
    else:
        for i in range(10):
            out[index] = chr(i + ord('0'))
            findNDigitNumsUtil(n, out, index + 1, evenSum + i, oddSum)


def findNDigitNums(n):
    out = [0] * (n + 1)
    index = 0
    evenSum = 0
    oddSum = 0
    for i in range(1, 10):
        out[index] = chr(i + ord('0'))
        findNDigitNumsUtil(n, out, index + 1, evenSum + i, oddSum)


if __name__ == "__main__":
    n = 3
    findNDigitNums(n)

# Expected output:
100
111
120
122
131
133
142
144
153
155
164
166
175
177
186
188
197
199
210
221
230
232
241
243
252
254
263
265
274
276
285
287
296
298
320
331
340
342
351
353
362
364
373
375
384
386
395
397
430
441
450
452
461
463
472
474
483
485
494
496
540
551
560
562
571
573
582
584
593
595
650
661
670
672
681
683
692
694
760
771
780
782
791
793
870
881
890
892
980
991
# program to convert a given number to words | set 2 | strings at index 0 is not used , it is to make array indexing simple ; strings at index 0 and 1 are not used , they is to make array indexing simple ; n is 1 - or 2 - digit number ; if n is more than 19 , divide it ; if n is non - zero ; function to print a given number in words ; stores word representation of given number n ; handles digits at ten millions and hundred millions places ( if any ) ; handles digits at hundred thousands and one millions places ( if any ) ; handles digits at thousands and tens thousands places ( if any ) ; handles digit at hundreds places ( if any ) ; handles digits at ones and tens places ( if any ) ; long handles upto 9 digit no change to unsigned long long int to handle more digit number ; convert 

one = [
    "",
    "one ",
    "two ",
    "three ",
    "four ",
    "five ",
    "six ",
    "seven ",
    "eight ",
    "nine ",
    "ten ",
    "eleven ",
    "twelve ",
    "thirteen ",
    "fourteen ",
    "fifteen ",
    "sixteen ",
    "seventeen ",
    "eighteen ",
    "nineteen "]
ten = [
    "",
    "",
    "twenty ",
    "thirty ",
    "forty ",
    "fifty ",
    "sixty ",
    "seventy ",
    "eighty ",
    "ninety "]


def numToWords(n, s):
    str = ""
    if (n > 19):
        str += ten[n // 10] + one[n % 10]
    else:
        str += one[n]
    if (n):
        str += s
    return str


def convertToWords(n):
    out = ""
    out += numToWords((n // 10000000), "crore ")
    out += numToWords(((n // 100000) % 100), "lakh ")
    out += numToWords(((n // 1000) % 100), "thousand ")
    out += numToWords(((n // 100) % 10), "hundred ")
    if (n > 100 and n % 100):
        out += "and "
    out += numToWords((n % 100), "")
    return out


n = 438237764
print(convertToWords(n))

# Expected output:
forty three crore eighty two lakh thirty seven thousand seven hundred and sixty four
# find number of subarrays with even sum | python 3 program to count number of sub - arrays with even sum using an efficient algorithm time complexity - o ( n ) space complexity - o ( 1 ) ; result may be large enough not to fit in int ; ; to keep track of subarrays with even sum starting from index i ; if a [ i ] is odd then all subarrays starting from index i + 1 which was odd becomes even when a [ i ] gets added to it . ; if a [ i ] is even then all subarrays starting from index i + 1 which was even remains even and one extra a [ i ] even subarray gets added to it . ; 
def countEvenSum(arr, n):
    res = 0
    s = 0
    for i in reversed(range(n)):
        if arr[i] % 2 == 1:
            s = n - i - 1 - s
        else:
            s = s + 1
        res = res + s
    return res


if __name__ == "__main__":
    arr = [1, 2, 2, 3, 4, 1]
    n = len(arr)
    print("The Number of Subarrays with even" " sum is", countEvenSum(arr, n))

# Expected output:
The Number of Subarrays with even sum is 9
# linear diophantine equations | python 3 program to check for solutions of diophantine equations ; this function checks if integral solutions are possible ; 

from math import gcd


def isPossible(a, b, c):
    return (c % gcd(a, b) == 0)


if __name__ == '__main__':
    a = 3
    b = 6
    c = 9
    if (isPossible(a, b, c)):
        print("Possible")
    else:
        print("Not Possible")
    a = 3
    b = 6
    c = 8
    if (isPossible(a, b, c)):
        print("Possible")
    else:
        print("Not Possible")
    a = 2
    b = 5
    c = 1
    if (isPossible(a, b, c)):
        print("Possible")
    else:
        print("Not Possible")

# Expected output:
Possible
Not Possible
Possible
# farey sequence | efficient python3 program to print farey sequence of order n ; optimized function to print farey sequence of order n ; we know first two terms are 0 / 1 and 1 / n ; for next terms to be evaluated ; using recurrence relation to find the next term ; print next term ; update x1 , y1 , x2 and y2 for next iteration ; 

import math


def farey(n):
    x1 = 0
    y1 = 1
    x2 = 1
    y2 = n
    print(x1, end="")
    print("/", end="")
    print(y1, x2, end="")
    print("/", end="")
    print(y2, end=" ")
    x = 0
    y = 0
    while (y != 1.0):
        x = math .floor((y1 + n) / y2) * x2 - x1
        y = math .floor((y1 + n) / y2) * y2 - y1
        print(x, end="")
        print("/", end="")
        print(y, end=" ")
        x1 = x2
        x2 = x
        y1 = y2
        y2 = y


n = 7
print("Farey Sequence of order", n, "is")
farey(n)

# Expected output:
Farey Sequence of order 7 is
0/1 1/7 1/6 1/5 1/4 2/7 1/3 2/5 3/7 1/2 4/7 3/5 2/3 5/7 3/4 4/5 5/6 6/7 1/1
# find smallest values of x and y such that ax | to find gcd using eculcid 's algorithm ; prints smallest values of x and y that satisfy " ax ▁ - ▁ by ▁ = ▁ 0" ; find lcm ; 
def gcd(a, b):
    if (b == 0):
        return a
    return (gcd(b, a % b))


def findSmallest(a, b):
    lcm = (a * b) / gcd(a, b)
    print("x =", lcm / a, "y=", lcm / b)


a = 25
b = 35
findSmallest(a, b)

# Expected output:
x = 7.0 y= 5.0
# count number of ways to divide a number in 4 parts | returns count of ways ; generate all possible quadruplet and increment counter when sum of a quadruplet is equal to n ; 
def countWays(n):
    counter = 0
    for i in range(1, n):
        for j in range(i, n):
            for k in range(j, n):
                for l in range(k, n):
                    if (i + j + k + l == n):
                        counter += 1
    return counter


if __name__ == "__main__":
    n = 8
    print(countWays(n))

# Expected output:
5
# sum of bitwise and of all pairs in a given array | returns value of " arr [ 0 ] ▁ & ▁ arr [ 1 ] ▁ + ▁ arr [ 0 ] ▁ & ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ & ▁ arr [ j ] ▁ + ▁ . . . . . ▁ arr [ n - 2 ] ▁ & ▁ arr [ n - 1 ] " ; consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; 
def pairAndSum(arr, n):
    ans = 0
    for i in range(0, n):
        for j in range((i + 1), n):
            ans = ans + arr[i] & arr[j]
    return ans


arr = [5, 10, 15]
n = len(arr)
print(pairAndSum(arr, n))

# Expected output:
15
# sum of bitwise and of all pairs in a given array | returns value of " arr [ 0 ] ▁ & ▁ arr [ 1 ] ▁ + ▁ arr [ 0 ] ▁ & ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ & ▁ arr [ j ] ▁ + ▁ . . . . . ▁ arr [ n - 2 ] ▁ & ▁ arr [ n - 1 ] " ; traverse over all bits ; count number of elements with i 'th bit set  initialize the count ; there are k set bits , means k ( k - 1 ) / 2 pairs . every pair adds 2 ^ i to the answer . therefore , we add "2 ^ i ▁ * ▁ [ k * ( k - 1 ) / 2 ] " to the answer . ; 
def pairAndSum(arr, n):
    ans = 0
    for i in range(0, 32):
        k = 0
        for j in range(0, n):
            if ((arr[j] & (1 << i))):
                k = k + 1
        ans = ans + (1 << i) * (k * (k - 1) // 2)
    return ans


arr = [5, 10, 15]
n = len(arr)
print(pairAndSum(arr, n))

# Expected output:
15
# primality test | set 1 ( introduction and school method ) | a school method based python3 program to check if a number is prime ; corner case ; check from 2 to n - 1 ; 
def isPrime(n):
    if n <= 1:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True


print("true")if isPrime(11)else print("false")
print("true")if isPrime(14)else print("false")

# Expected output:
true
false
# euler 's totient function for all numbers smaller than or equal to n | computes and prints totient of all numbers smaller than or equal to n . ; create and initialize an array to store phi or totient values ; compute other phi values ; if phi [ p ] is not computed already , then number p is prime ; phi of a prime number p is always equal to p - 1. ; update phi values of all multiples of p ; add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; print precomputed phi values ; 
def computeTotient(n):
    phi = []
    for i in range(n + 2):
        phi .append(0)
    for i in range(1, n + 1):
        phi[i] = i
    for p in range(2, n + 1):
        if (phi[p] == p):
            phi[p] = p - 1
            for i in range(2 * p, n + 1, p):
                phi[i] = (phi[i] // p) * (p - 1)
    for i in range(1, n + 1):
        print("Totient of ", i, " is ", phi[i])


n = 12
computeTotient(n)

# Expected output:
Totient of  1  is  1
Totient of  2  is  1
Totient of  3  is  2
Totient of  4  is  2
Totient of  5  is  4
Totient of  6  is  2
Totient of  7  is  6
Totient of  8  is  4
Totient of  9  is  6
Totient of  10  is  4
Totient of  11  is  10
Totient of  12  is  4