/*---------------------------------------------------------------------------
File name: 648.c
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 8/30/2007 08:12:36
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
Modification history:
===========================================================================
Problem statement:
---------------------------------------------------------------------------
http://bbs.bc-cn.net/viewthread.php?tid=166576
已知n/2是完全平方数,n/3是立方数,编写一个程序求最小的正整数n。
Analysis:
---------------------------------------------------------------------------
n/2=a*a
n/2=b*b*b
implies 2*a*a = 3*b*b*b.
雨中飞燕:
心算都可以了,只有一个数648
When it is said "最小的正整数n", it is certain we have at most one solution.
Sample output:
---------------------------------------------------------------------------
n=648
Press any key to continue . . .
*/
#include <stdio.h>
#include <math.h>
int main()
{
int a, b, c;
/**
for this kind of problem, you can apply binary search:
since
1, 4, 9, 16, 25, ...
1, 8, 27, 64, 125, ...
are ordered.
Following code does not use binary search, instead it is a
burte force search.
*/
for(b=1; b<100000; ++b)
{
c=(int)sqrt(1.5*b*b*b);
for(a=1; a<=c; ++a)
{
if(2*a*a==3*b*b*b)
{
printf("n=%d\n", 2*a*a);
return 0;
}
}
}
return 0;
}
[此贴子已经被作者于2007-8-30 23:16:24编辑过]
楼上,利害!!
我也写了一个,效率太低,,呵呵
//这个数必然是6的倍数
#include <iostream>
#include <cmath>
using namespace std ;
bool IsThree(const int n)
{
int i ;
bool res = false ;
for(i=2; i<n/3; i+=2)
{
if(i*i*i == n)
{
res = true ;
return res ;
}
}
return res ;
}
bool IsTwo(const int n)
{
int i ;
bool res = false ;
if(sqrt(n) == (int)sqrt(n))
{
res = true ;
}
return res ;
}
void GetNum(int &num)
{
while(!(IsTwo(num/2) && IsThree(num/3)))
{
num += 6;
}
}
int main()
{
int m_num = 6 ;
GetNum(m_num) ;
cout << m_num << endl ;
return 0 ;
}
[此贴子已经被作者于2007-8-31 0:06:39编辑过]