imtheonly1's blog

By imtheonly1, history, 3 months ago, In English

What mistake I'm Doing?

The python code is working fine but C++ doesn't.

PYTHON

N = 1000000000000000000
i = 2
c = 0
while 1 + i + i * i + i * i * i <= N:
    temp = 1 + i + i * i + i * i * i
    x = i * i * i
    while temp <= N:
        c += 1
        x = x * i
        temp = temp + x
    i += 1
print(c)
# OUPTUT
# 1037545

# =====
# Used: 936 ms, 0 KB

CPP

// author: imtheonly1
// time: 2024-07-28 19:33:55
//
// Problem: E2. Rudolf and Snowflakes (hard version)
// URL: https://codeforces.me/contest/1846/problem/E2
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include <iostream>
#include <cmath>

int main() {
    long long N = 1000000000000000000LL; // 1e18
    long long i = 2;
    long long c = 0;
    
    while (1 + i + i * i + i * i * i <= N) {
        long long temp = 1 + i + i * i + i * i * i;
        long long x = i * i * i;
        
        while (temp <= N) {
            c++;
            x = x * i;
            temp = temp + x;
        }
        
        i++;
    }
    
    std::cout << c << std::endl;
    return 0;
}
// OUTPUT
// Invocation failed [TIME_LIMIT_EXCEEDED]

// Runtime error: exit code is -1
// =====
// Used: 15000 ms, 0 KB

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
3 months ago, # |
  Vote: I like it +1 Vote: I do not like it

most likely overflow issues

»
3 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Debugged your code, and operations you doing can become extremely large,sorry use __int128

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

temp and x vars are too large (1e19) use __int128

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Overflow of expression x = x * i;, with __int128 works in milliseconds.