吸血鬼数字和Fibonacci数列
简单的Java程序
1.吸血鬼数字
吸血鬼数字就是指位数为偶数的数字,可以由一对数字相乘而得到,而对这数字各包含乘积
的一半位数的数字,其中从最初的数字中选取的数字可以任意排序。以两个0结尾的数字是
不允许的,例如:下列数字就是“吸血鬼“数字:
1260 = 21*60
1827 = 21*87
2187 = 27*81
写出一个程序,找出4位数的所有吸血鬼数字(Dan Forhan推荐) import java.applet.*;
import java.awt.*;
public class Vampire extends Applet {
private static final long serialVersionUID = 1L;
private int num1, num2, product;
private int[] startDigit = new int[4];
private int[] productDigit = new int[4];
private int count = 0;
private int vampCount = 0;
private int x, y;
public void paint(Graphics g) {
g.drawString("Vampire Numbers ", 10, 20);
g.drawLine(10, 22, 150, 22);
int column = 10, row = 35;
for (num1 = 10; num1 <= 99; num1++)
for (num2 = 10; num2 <= 99; num2++) {
product = num1 * num2;
startDigit[0] = num1 / 10;
startDigit[1] = num1 % 10;
startDigit[2] = num2 / 10;
startDigit[3] = num2 % 10;
productDigit[0] = product / 1000;
productDigit[1] = (product % 1000) / 100;
productDigit[2] = product % 1000 % 100 / 10;
productDigit[3] = product % 1000 % 100 % 10;
count = 0;
for (x = 0; x < 4; x++)
for (y = 0; y < 4; y++) {
if (productDigit[x] == startDigit[y]) {
count++;
productDigit[x] = -1;
startDigit[y] = -2;
if (count == 4) {
vampCount++;
@SuppressWarnings("unused")
int a = (int) Math.random() * 100; 运行结果: @SuppressWarnings("unused")
int b = (int) Math.random() * 100;
@SuppressWarnings("unused")
int c = (int) Math.random() * 100;
if (vampCount < 10) {
g.drawString("Vampire number "
+ vampCount + " is " + num1
+ " * " + num2 + " = "
+ product, column, row);
row += 20;
} else {
g.drawString("Vampire number "
+ vampCount + " is " + num1
+ " * " + num2 + " = "
+ product, column, row);
row += 20;
}
}
}
}
}
}
}
2.一个斐波那契数列是有数字1、1、2、3、5、8、13、21、34等等数字组成的,其中每一个数字,(从第三个数字起)都是前两个数字的和。创建一个
,接受一个整数参数,并显示从第一个元素开始总共有该参数指定的个数所构成的所有的斐波那契数字。 package tyf;
public class Fiboncacci {
/* 输出斐波那契数 */
public static void printFibonacciNumber(long f1, long f2, int n) { System.out.print("Fiboncacci数列(前20位):");
for (int i = 1; i <= n; i++) {
System.out.print(f1 + " " + f2 + " ");// 先输出前两个数
if (i % 10 == 0)
System.out.print("\n"); // 换行
f1 = f1 + f2; // 计算下两个数
f2 = f1 + f2;
}
/* 后数除前数为黄金分割点 */
// System.out.print("\n" +----------------------------" +"\n");
// System.out.println((double) f2 / f1);// 越到后边,后数除前数越接近黄金分割点
}
/* 输出斐波那契数组 */
public static void printFibonacciArray(long f1, long f2, int n) {
long f[] = new long[n];
f[0] = f1;
f[1] = f2;
for (int i = 2; i < n; i++) {
f[i] = f[i - 2] + f[i - 1]; // 数组的第三个数开始为前两个数的和
}
// System.out.println("------------------------------" + "\n");
// System.out.println(java.util.Arrays.toString(f)); // 把数组转化成String输出
}
public static void main(String[] args) {
Fiboncacci.printFibonacciNumber(0, 1, 10);// print the 20 advanced fibonacci number
Fiboncacci.printFibonacciArray(0, 1, 20);
}
}
运行结果: