-1
input_numbers=list(map(int,input().split()))
sum_number=0

def my_gen(a):
    i=0
    while i <= a:
        yield i
        i += 1

for i in my_gen(input_numbers[0]):
    sum_number += i**input_numbers[1]

print(sum_number%1000000009)

I tried not using generator, but it was too slow. so, tried again with generator and it was slow too.

How can I make this faster?//

More information: My scoring bot is saying Time out. and (1<=input_numbers[0]<=1,000,000,000) (1<=input_numbers[1]<=50)

& Numpy cant be used

elon jeong
  • 69
  • 1
  • 5

3 Answers3

4

You can use Faulhaber's formula which will only require a loop over the power value (rather than the billion numbers from 0 to N).

from fractions import Fraction
from functools import lru_cache
@lru_cache()
def bernoulli(n,result=True): # optimized version
    A = [Fraction(1,n+1)]
    for j,b in enumerate(bernoulli(n-1,False) if n else []):
        A.append((n-j)*(b-A[-1]))
    return A[-1] if result else A

@lru_cache()
def comb(n,r):
    return 1 if not r else comb(n,r-1)*(n-r+1)//r

def powerSum(N,P):
    result = sum(comb(P+1,j) * bernoulli(j) * N**(P+1-j) for j in range(P+1))
    return (result / (P+1)).numerator

output:

powerSum(100,3) # 25502500

sum(i**3 for i in range(100+1)) # 25502500 (proof)

powerSum(1000000000,50)%1000000009 
# 265558322 in 0.016 seconds on my laptop

sum(i**50 for i in range(1000000000+1))%1000000009 
# 265558322 (proof in 16.5 minutes)
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • I wrote a version [using ints modulo 1000000009 instead of fractions](https://preview.tinyurl.com/y77dyqew) now, seems to be about 15 times faster on that large case (see benchmark results near the bottom there). – Kelly Bundy Jan 02 '21 at 22:07
  • Thx alot! It is really helpful! – elon jeong Jan 04 '21 at 04:14
0

The code is slow because you're taking large exponents of large numbers. But the final output doesn't require the full sum, just the modulo. So you can apply basic modular arithmetic to keep the numbers in your calculation smaller while getting the same final answer.

Burrito
  • 1,475
  • 19
  • 27
0

This is the bad part of problem: https://projecteuler.net/problem=429 But the good parts is to solve it yourself.

Glauco
  • 1,385
  • 2
  • 10
  • 20