Example #1
0
/* next function is adapted from:
   Inline C++ integer exponentiation routines 
   Version 1.01
   Copyright (C) 1999-2004 John C. Bowman <*****@*****.**>
*/
static inline Int
ipow(Int x, Int p)
{
  Int r;

  if (p == 0) return ((CELL)1);
  if (x == 0 && p > 0) return 0L;
  if(p < 0) 
    return (-p % 2) ? x : ((CELL)1);
	
  r = ((CELL)1);
  for(;;) {
    if(p & 1) {
      if (mul_overflow((r*x), r, x)) {
	return 0;
      }
      r *= x;
    }
    if((p >>= 1) == 0)	return r;
    if (mul_overflow((x*x), x, x)) {
      return 0;
    }
    x *= x;
  }
}
__int64 solve_119()
{
	std::list<ui64_t> xlist;
	for(int base = 2; base < 500; ++base)
	{
		// 乘方的方式构造数,power必然是完全N次方数,需要检验的是它的DigitSum是否和它N次方的基数相等.
		for(ui64_t power = base * base; !mul_overflow(power, base); power *= base)
			if(digit_sum(power) == base)	// 按顺序插入.
				xlist.insert(std::lower_bound(xlist.begin(), xlist.end(), power), power);
	}
	int i = 0;
	std::list<ui64_t>::const_iterator ite = xlist.begin();
	for(; ite != xlist.end() && ++i < 30; ++ite)
		;
	return ite != xlist.end() ? *ite : 0;
}