给定两个整数“ X”和“ N”,任务是将整数“ X”分成正好为“ N”的部分,从而:
X1 + X2 + X3 + ... + Xn = X
并且序列中最大和最小数字之间的差异最小。
如果不能将数字精确地划分为“ N”个部分,则最后打印该序列,然后打印“ -1”。
例子:
Input: X = 5, N = 3
Output: 1 2 2
Divide 5 into 3 parts such that the difference between the largest and smallest integer among
them is as minimal as possible. So we divide 5 as 1 + 2 + 2.
Input: X = 25, N = 5
Output: 5 5 5 5 5
方法:如果X >= N
总是有一种分割数字的方法。
- 如果将数字精确地划分为“ N”个部分,则每个部分的值将为
X/N
,剩余的X%N
部分可以分配给任何X%N
数字。 - 因此,如果
X % N == 0
则最小差将始终为’0’,并且该序列将包含所有相等的数字,即x/n
。 - 否则,差将为“ 1”,并且序列将为
X/N, X/N, ..., (X/N)+1, (X/N)+1.
。
下面是上述方法的实现:
C++
// CPP implementation of the approach
#include
using namespace std;;
// Function that prints
// the required sequence
void split(int x, int n)
{
// If we cannot split the
// number into exactly 'N' parts
if(x < n)
cout<<"-1"<<" ";
// If x % n == 0 then the minimum
// difference is 0 and all
// numbers are x / n
else if (x % n == 0)
{
for(int i=0;i= zp)
cout<<(pp + 1)<<" ";
else
cout<
Java
// Java implementation of the approach
class GFG{
// Function that prints
// the required sequence
static void split(int x, int n)
{
// If we cannot split the
// number into exactly 'N' parts
if(x < n)
System.out.print("-1 ");
// If x % n == 0 then the minimum
// difference is 0 and all
// numbers are x / n
else if (x % n == 0)
{
for(int i=0;i= zp)
System.out.print((pp + 1)+" ");
else
System.out.print(pp+" ");
}
}
}
// Driver code
public static void main(String[] args)
{
int x = 5;
int n = 3;
split(x, n);
}
}
//This code is contributed by mits
Python3
# Python3 implementation of the approach
# Function that prints
# the required sequence
def split(x, n):
# If we cannot split the
# number into exactly 'N' parts
if(x < n):
print(-1)
# If x % n == 0 then the minimum
# difference is 0 and all
# numbers are x / n
elif (x % n == 0):
for i in range(n):
print(x//n, end =" ")
else:
# upto n-(x % n) the values
# will be x / n
# after that the values
# will be x / n + 1
zp = n - (x % n)
pp = x//n
for i in range(n):
if(i>= zp):
print(pp + 1, end =" ")
else:
print(pp, end =" ")
# Driver code
x = 5
n = 3
split(x, n)
C#
// C# implementation of the approach
using System;
public class GFG{
// Function that prints
// the required sequence
static void split(int x, int n)
{
// If we cannot split the
// number into exactly 'N' parts
if(x < n)
Console.WriteLine("-1 ");
// If x % n == 0 then the minimum
// difference is 0 and all
// numbers are x / n
else if (x % n == 0)
{
for(int i=0;i= zp)
Console.Write((pp + 1)+" ");
else
Console.Write(pp+" ");
}
}
}
// Driver code
static public void Main (){
int x = 5;
int n = 3;
split(x, n);
}
}
//This code is contributed by Sachin.
PHP
= $zp)
{
echo (int)$pp + 1;
echo (" ");
}
else
{
echo (int)$pp;
echo (" ");
}
}
}
}
// Driver code
$x = 5;
$n = 3;
split( $x, $n);
// This code is contributed
// by Shivi_Aggarwal
?>
输出:
1 2 2