# Project Euler：Problem 57 Square root convergents

It is possible to show that the square root of two can be expressed as an infinite continued fraction.

√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...

By expanding this for the first four iterations, we get:

1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...

The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.

In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?

#include <iostream>
#include <string>
using namespace std;

string strplus(string a, string b)
{
int lena = a.length();
int lenb = b.length();
int len;
if (lena <= lenb)
{
int gap = lenb - lena;
string c;
c.resize(gap, '0');
a = c + a;
len = lenb;
}
else
{
int gap = lena - lenb;
string c;
c.resize(gap, '0');
b = c + b;
len = lena;
}
int flag = 0;
string ans = "";
for (int i = len - 1; i >= 0; i--)
{
int tmp = a[i] + b[i] - '0' - '0' + flag;
flag = tmp / 10;
tmp = tmp % 10;
char p = tmp + '0';
ans = p + ans;
}
if (flag == 1)
ans = '1' + ans;
return ans;
}

int main()
{
string a = "3";
string b = "2";
int count = 0;
for (int i = 2; i <= 1000; i++)
{
string tmp = b;
b = strplus(a, b);
a = strplus(b, tmp);
if (a.length() > b.length())
count++;
}
cout << count << endl;
system("pause");
return 0;
}


• 本文已收录于以下专栏：

## Project Euler Problem 51-70

• u011401504
• 2015年02月08日 02:22
• 1695

## Project-Euler problem 1-50

• u011401504
• 2015年01月31日 00:09
• 2038

## Project Euler Problem 57

Project Euler Problem 57  这个要深入研究一下。。。。我是暴力写的。。太对不起人了。。。以后再改。。。最近也在看连分数。。但是还是太囧。。下面是在论坛讨论上大家的讨论。。以后...
• sosidami
• 2009年10月24日 20:38
• 484

## Project Euler 57

• lushl9301
• 2012年12月02日 20:44
• 159

## Project Euler problem 57

• sdj222555
• 2012年11月07日 09:13
• 379

## project euler 解题

project euler 3：Any integer greater than 1 is either a prime number, or can be written as a unique p...
• cctvzxxz1
• 2013年06月23日 20:25
• 3586

## Project Euler ：Problem 54 Poker hands

In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the...
• youb11
• 2015年07月07日 14:50
• 720

## Project Euler：Problem 65 Convergents of e

The square root of 2 can be written as an infinite continued fraction. √2 = 1 + 1 ...
• youb11
• 2015年07月15日 14:57
• 620

## Project Euler：Problem 89 Roman numerals

For a number written in Roman numerals to be considered valid there are basic rules which must be fo...
• youb11
• 2015年07月24日 16:44
• 569

## spring源码导入eclipse，A problem occurred configuring project ':spring-orm-hibernate4'.

• fuxitao
• 2017年03月06日 10:46
• 564

举报原因： 您举报文章：Project Euler：Problem 57 Square root convergents 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)