Official

A - 3.14 Editorial by en_translator


For beginners

Print the first \((N+2)\) characters of the string "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679".

This can be done with a loop with \((N+2)\) iterations.

If your language has a feature that yields the string consisting of the first \(k\) characters of a string \(S\), you can also use it to solve this problem. (In C++, you can use std::string::substr; in Python, you can use a slice.)

The following are sample codes. We introduce implementations that does and does not use loop in C++ and Python.

Implementation using loop

C++

#include <string>
#include <iostream>

using namespace std;

int main() {
    string pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";

    int N;
    cin >> N;

    for (int i = 0; i < N + 2; ++i) // Print the first N+2 characters
        cout << pi[i];

    cout << endl;

    return 0;
}

Python

pi = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679'
N = int(input())

for i in range(N + 2):
    print(pi[i], end='')

Implementation without loop

C++

#include <string>
#include <iostream>

using namespace std;

int main() {
    string pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";

    int N;
    cin >> N;

    cout << pi.substr(0, N + 2) << endl;

    return 0;
}

Python

pi = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679'
N = int(input())

print(pi[:N + 2])

posted:
last update: