python埃及分数式_埃及分数式

夏虫

package com.test;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Main main = new Main();

Scanner sc = new Scanner(System.in);

System.out.print("请输入测试组数:");

int t = sc.nextInt();

System.out.print("请输入" + t + "个真分数(如3/7):\n");

String[] strs = new String[t];

String[] results = new String[t];

for (int i = 0; i 

System.out.print("第" + (i + 1) + "个分数:");

strs[i] = sc.next();

results[i] = main.getResult(strs[i]);

while (results[i] == null) {

System.out.print("输入错误,请重新输入第" + (i + 1) + "个分数:");

strs[i] = sc.next();

results[i] = main.getResult(strs[i]);

}

}

for (int i = 0; i 

System.out.println(strs[i] + "=" + results[i]);

}

}

public String getResult(String str) {

String result = "";

String[] strs = str.split("/");

if (strs.length != 2) {

return null;

}

long a, b;

try {

a = Integer.valueOf(strs[0]);

b = Integer.valueOf(strs[1]);

if (a >= b || a <= 0 || b <= 0) {

return null;

}

long[] I = simple(a, b);

if (a != I[0]) {

a = I[0];

b = I[1];

result = a + "/" + b + "=";

}

while (a != 1) {

long temp = b / a + 1;

result = result + "1/" + temp + "+";

a = a * temp - b;

b = b * temp;

I = simple(a, b);

a = I[0];

b = I[1];

}

if (a == 1) {

result = result + "1/" + b;

}

} catch (Exception e) {

return null;

}

return result;

}

public long[] simple(long a, long b) {

for (long i = a; i > 1; i--) {

if (b % i == 0 && a % i == 0) {

a = a / i;

b = b / i;

simple(a, b);

}

}

return new long[]{a, b};

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值