大数运算,用JAVA的话几行代码就搞定了,但这是我的500题里程碑,不能就这么偷懒了!要为今后树立榜样!果断用C++重写了,我的思路把大数除法转化成小数阶乘1/2^N就是运算(0.5)^N,进而转化为5的幂次,0的位数什么的另外再算算就好了,不知道这样能不能比直接算效率高一点,代码都附上吧。
顺便500题AC达成了,从去年12月开始到现在也有9个月的时间了,我觉得自己的代码能力还是有进步的,毕竟一行代码就有一行代码的积累,没有统计过代码量,但是500题怎么说也有3W行左右的代码,虽然说500题中水题占了绝大多数。。也还是能从题目中了解不少的算法的,从以前对BFS,DFS这些一无所知到现在写简单的搜索算法已经很熟练了,思路上也开阔了不少,还有图论,数据结构,大数,DP方面都有一定涉猎,以前写JAVA代码的时候从来没从内存方面考虑过代码的质量,毕竟C/C++的使用肯定能对内存使用的敏感度有提升,也不多说了,仅以此500题献给曾经在ZJU逝去的青春,以及勉励未来的自己,希望有朝一日如果有可能,我能超越一个又一个的前辈们,进入ZOJ的第一版,哇哈哈!愿代码与你我同在,加油!
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
namespace
{
string power(int base, int p)
{
string res = "1", temp;
int carry, t;
while (p--)
{
temp.clear();
carry = 0;
for (size_t i = 0; i < res.size(); i++)
{
t = base * (res[i] - '0') + carry;
carry = t / 10;
temp += t % 10 + '0';
}
if (carry)
temp += carry + '0';
res = temp;
}
reverse(res.begin(), res.end());
return res;
}
string& remove_leading_zero(string &s)
{
while (s[0] == '0')
s.erase(0, 1);
return s;
}
int calc(const string &str, int base)
{
string temp, s = str;
int res = 0;
while (s != "1")
{
temp.clear();
int rem = 0;
for (size_t i = 0; i < s.size(); i++)
{
rem = rem * 10 + (s[i] - '0');
temp += (rem / base + '0');
rem = rem % base;
}
remove_leading_zero(temp);
s = temp;
res++;
}
return res;
}
int remove_tail_zero(string &s)
{
int end = s.size(), count = 0;
while (s[--end] == '0')
count++;
s.erase(end + 1, count);
return count;
}
void print_zero(int n)
{
while (n--)
putchar('0');
}
}
int main()
{
puts("Problem 4 by team x");
string s;
while (cin >> s)
{
printf("\n1 / %s =\n", s.c_str());
int tail = remove_tail_zero(s);
putchar('0');
putchar('.');
if (s[s.size() - 1] == '1')
{
print_zero(tail - 1);
puts("1");
}
else
{
int base = s[s.size() - 1] == '5' ? 5 : 2;
int p = calc(s, base);
string pow = power(10 / base, p);
print_zero(tail + p - pow.size());
puts(pow.c_str());
}
}
puts("End of problem 4 by team x");
return 0;
}
JAVA偷懒版代码。。
import java.math.BigDecimal;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Problem 4 by team x");
while (sc.hasNextLine())
{
String line = sc.nextLine();
System.out.format("\n1 / %s =\n", line);
System.out.println(BigDecimal.ONE.divide(new BigDecimal(line))
.toPlainString());
}
System.out.println("End of problem 4 by team x");
sc.close();
}
}