JAVA算法：埃及分数（Egyptian Fraction）

JAVA算法：埃及分数（Egyptian Fraction）

• 2/3 等价于 1/2 + 1/6
• 6/14 等价于 1/3 + 1/11 + 1/231
• 12/13 等价于 1/2 + 1/3 + 1/12 + 1/156

package com.bean.algorithmbasic;

public class EgyptFractionDemo3 {

/*
* numerator 代表分子
* denominator 代表分母
*
*
* 例如: numerator = 2 ; denominator =4
* 2/4  进行约分
* 2/5  进行计算
*
* */
public static void egyptFraction(int numerator, int denominator) {

int total=0; //计数器
System.out.print(numerator + "/" + denominator + "=");
while(true) {
/* 如果分子能够整除分母,则对原分数进行约分 , 保持分子为1 */
if (denominator % numerator == 0) {
denominator = denominator / numerator;
numerator = 1;
}

/* 分子为1时,直接输出结果,中止循环 */
if (numerator == 1) {
System.out.print(numerator + "/" + denominator);
total++;
break;
} else {
/* 保留原有的分子与分母的值 */
int d = denominator;
int n = numerator;

/* 得到比当前分数小的最大埃及分数的分母,并输出找到的最大埃及数 */
int num = denominator / numerator + 1;
System.out.print(1 + "/" + num + "+");
total++;

/* 得到余数的分子与分母,继续循环 */
denominator = d * num;
numerator = n * num - d;
}
}
System.out.println();
System.out.println("可分解为埃及数的个数为: " + total);
}

public static void main(String[] args) {

int numerator = 2;
int denominator = 5;
egyptFraction(numerator,denominator);
}

}


2/5=1/3+1/15

DFS算法设计

package com.bean.algorithmbasic;

public class EgyptFractionDemo2 {

static int N=100000;
static int[] array=new int[N];

public static void main(String [] args){
int nums1 = 2;
int nums2 = 15;
for(int i=1;;i++) {
if(dfs(0,i,nums1,nums2)==1) {
break;
}
}

}

/*
* 用于进行判断
* */
public static double is_equal(int a, int b, int cur)
{
double sum = 0;
for (int i = 0; i <= cur; i++)
sum += (double)1 / array[i];
return (double)a / b - sum;
}

public static int dfs(int cur, int d, int a, int b)
{
if (cur == d)
return 0;
int start = (int) ((int)(d - cur) / (is_equal(a, b, cur - 1)));
int end = cur == 0 ? 2 : array[cur-1] + 1;
for (int i = start;i>=end; i--)
{
array[cur] = i;
double p = is_equal(a, b, cur);
if (Math.abs(p) <= 0.00001)
{
for (int j = 0; j <= cur; j++)
System.out.print(array[j]+" ");
System.out.println();
return 1;
}
else if (p > 0)
{
if (dfs(cur + 1, d, a, b)!=0)
return 1;
}
}
return 0;
}

}


package com.bean.algorithmbasic;

public class EgyptFractionDemo {

public static void main(String [] args){
int nums1 = 2;
int nums2 = 15;
egyptFraction(nums1, nums2);
}

public static void egyptFraction(int num1, int num2){
int maxComDiv = 0;
while(num1 > 1){
trade = num2 / num1 + 1;
num1 = num1 * trade - num2;
maxComDiv = maxComDiv(num1, num2);
if(maxComDiv > 1){
num1 = num1 / maxComDiv;
num2 = num2 / maxComDiv;
}
}
System.out.println(1 + "/" + num2);
}

public static int maxComDiv(int num1, int num2) {
int remaind = 0;
while(num2 != 0){
remaind = num1 % num2;
num1 = num2;
num2 = remaind;
}
return num1;
}

}


12-16

07-12 7058
02-12 5437
01-28 616
11-30 1920