Ni Wendi accompanies you to learn Blue Bridge Cup 2021 winter vacation daily question: 1.13 (2018 provincial competition group A question 1)

One question per day for the winter vacation in 2021, and the real question for the provincial competition from 2017 to 2019.
The content of this article is provided by Ni Wendi (Software Class 192, Department of Computer Science, East China University of Science and Technology) and Luo Yongjun.
In the following daily questions, each question will post a new blog post. Please read the blog Blue Bridge Cup column every day : https://blog.csdn.net/weixin_43914593/category_10721247.html

Each question provides code in three languages: C++, Java, and Python .

Question 1 of Group A of the 2018 Provincial Competition, link to the question:
Scorehttp : //oj.ecustacm.cn/problem.php ?id=1359

1. Description of the topic


1/1 + 1/2 + 1/4 + 1/8 + 1/16 + …
Each item is half of the previous item, if there are 20 items in total, what is the sum, and the result is expressed as a fraction.
Similar: 3/2 Of course, this just adds the first 2 items. The numerator and denominator are required to be coprime.


2. Problem solving

  Ni Wendi said: "This problem is divided, and then summing the proportional sequence, the original formula can be simplified. Then calculate the numerator and denominator through bit operation or exponentiation, and then remove the greatest common divisor of the two, and output That's it."
  Teacher Luo had nothing to say.
  Forget it, let me say one more thing: Note that binary has a basic feature, 1 + 2 + 4 + . . . + 2 n = 2 n + 1 − 1 1+2+4+...+2^n=2^ {n+1}-11+2+4+...+2n=2n+11

3. C++ code

  In the code, gcd is used to calculate the greatest common divisor for reduction, so that the numerator and denominator are relatively prime. However, in fact, there is no need to reduce it, because it is mutually prime.

#include<bits/stdc++.h>
using namespace std;

int main(){
    
    
	int a = (1 << 20) - 1; //分子
	int b = (1 << 19);     //分母
	int t = __gcd(a, b);   //除去公约数
	cout << a/t << "/" << b/t;
	return 0;
}

4. Java code

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int a=(int) Math.pow(2, 20)-1;
        int b=(int) Math.pow(2, 19);
        System.out.println(a + "/" + b);
    }  
}

5. Python code

  Or Python is better. If you write one C++ and Java, you can write 4 Pythons.

b = 0
a = 1
for i in range(0,20):
    b += a
    a *= 2
print('%d/%d'%(b,a/2))
print('%d/%d'%(2 ** 20 -1,2 ** 19))
print(str(2 ** 20 -1)+'/'+str(2 ** 19))
print('%d/%d'% (pow(2,20)-1 ,pow(2,19)))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324135778&siteId=291194637