【程序1】 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第四个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
2 就是第三个数是前两个数字的和,既是经典的菲波那切数列
function actionFblist($n)
{
// 1,1,2,3,5,8,13
// $n 为第n个月
$arr = [1,1];
if($n < 2)
return false;
for ($i=2;$i<=$n+1;$i++)
{
$arr[$i] = $arr[$i-1] + $arr[$i-2];
}
var_dump($arr);
echo $arr[$n+1];
}
【程序2】 题目:判断101-200之间有多少个素数,并输出所有素数。
1.程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,
则表明此数不是素数,反之是素数。
public function actionIsPrimeNumber()
{
$arr = [];
for ($i=101;$i<=200;$i++)
{
$flag = true;
for ($j = 2;$j<=sqrt($i);$j++)
{
if($i % $j == 0)
{
$flag = false;
}
}
if($flag == true)
$arr[] = $i;
}
var_dump($arr);
}
【程序3】 题目:打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个 "水仙花数 ",因为153=1的三次方+5的三次方+3的三次方。
1.程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
public function actionWaterFlower()
{
$re = [];
for($i = 100;$i<= 999;$i++)
{
$hundred = floor($i / 100 ); // 获取百位数字
$ten = floor(($i %100 ) / 10 ); // 获取十位数字
$one = floor($i % 100 % 10); // 获取各位数字
if((pow($hundred,3) + pow($ten,3) + pow($one,3) ) == $i )
{
$re[] = $i;
}
}
var_dump($re);
}
【程序5】 题目:利用条件运算符的嵌套来完成此题:学习成绩> =90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
1.程序分析:(a> b)?a:b这是条件运算符的基本例子。
public function actionGetScore()
{
$score = 90;
if($score <0 || $score > 100)
return false;
$re = $score >= 90 ? 'A' : ($score >= 60 ? 'B' :'C');
var_dump($re);
}
【程序6】 题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
1.程序分析:利用辗除法。
最大公约数:
public class CommonDivisor{
public static void main(String args[])
{
commonDivisor(24,32);
}
static int commonDivisor(int M, int N)
{
if(N<0||M<0)
{
System.out.println("ERROR!");
return -1;
}
if(N==0)
{
System.out.println("the biggest common divisor is :"+M);
return M;
}
return commonDivisor(N,M%N);
}
}
最小公倍数和最大公约数:
import java.util.Scanner;
public class CandC
{
//下面的方法是求出最大公约数
public static int gcd(int m, int n)
{
while (true)
{
if ((m = m % n) == 0)
return n;
if ((n = n % m) == 0)
return m;
}
}
public static void main(String args[]) throws Exception
{
//取得输入值
//Scanner chin = new Scanner(System.in);
//int a = chin.nextInt(), b = chin.nextInt();
int a=23; int b=32;
int c = gcd(a, b);
System.out.pri

这篇博客包含了多个编程挑战,涉及斐波那契数列、素数判断、水仙花数、条件运算、最大公约数与最小公倍数、循环与递归等算法。通过解决这些题目,可以锻炼和提升编程逻辑和数学应用能力。
最低0.47元/天 解锁文章
272

被折叠的 条评论
为什么被折叠?



