试求和为N,积为最大的两个整数数分别是多少。

试求和为N,积为最大的两个整数数分别是多少。

从键盘中输入一个整数,它是另外两个整数的加法运算和,这样的两个整数的组合有很多种,请找出乘积最大的一组数据。请注意输出两个整数以空格分割,按由小到大的顺序输出。

输入格式:

从键盘中输入一个整数

输出格式:
在一行中输出两个整数,以空格分割,按由小到大的顺序输出。

输入样例:
33
输出样例:
16 17
输入样例:
-51
输出样例:
-26 -25

我的代码

	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		while(true)
		{
			int x = in.nextInt();
			if (x == 0)
			{
				System.out.println(-1 + " " + 1);
			} else if (x % 2 == 0)
			{
				System.out.println(x / 2 + " " + (x / 2));
			} else
			{
				if (x > 0)
				{
					System.out.println(x / 2 + " " + ((x / 2) + 1));
				} else
				{
					System.out.println((x / 2 - 1) + " " + ((x / 2)));
				}
			}
		}
	}

一些网上的代码,我做了些改进

	public static void main(String[] args)
	{

		Scanner xx = new Scanner(System.in);
		while(true)
		{
			int result1 = 0;
			int result2 = 0;
			int multiply = 0;
			int input =xx.nextInt();
			if(input==0)
			{
				result1 = -1;
				result2 = 1;
			}
			else if(input==1)
			{
				result1 = 0;
				result2 = 1;
			}
			else if(input==-1)
			{
				result1 = -1;
				result2 = 0;
			}
			else
			{
				int factor = input > 0 ? 1 : -1;
				while(true)
				{
					if (factor == input)
					{
						break;
					}
					if ((input - factor) * factor > multiply)
					{
						multiply = (input - factor) * factor;
						result1 = input - factor;
						result2 = factor;
					}
					if (input > 0)
					{
						factor++;
					} else
					{
						factor--;
					}
				}
			}
			/*
			 * 这里也可以进行修改一下,
			 * 因为当输入的数是正数时,result1是大的
			 * 当输入的是负数时,result1是小的数
			 */
			System.out.println(Integer.min(result1, result2) + " " + Integer.max(result1, result2));
		}
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ReflectMirroring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值