📌  相关文章
📜  查找N个整数,它们的乘积和总和之间具有给定差

📅  最后修改于: 2021-04-27 05:58:44             🧑  作者: Mango

给定两个整数N和D,请找到一组N个整数,使它们的乘积和之和等于D。
例子 :

Input : N = 2, D = 1
Output : 2 3
Explanation: 
product = 2*3 = 6,
Sum = 2 + 3 = 5.
Hence, 6 - 5 = 1(D).

Input : N = 3, D = 5.
Output : 1 2 8
Explanation :
Product = 1*2*8 = 16
Sum = 1+2+8 = 11.
Hence, 16-11 = 5(D).

一个棘手的解决方案是保持差D来选择N个数字作为N-2个“ 1”,一个“ 2”和一个剩余数字作为“ N + D”。
总和=(N-2)*(1)+ 2 +(N + D)= 2 * N + D.
乘积= 1 * 2 *(N + D)= 2 * N + 2 * D
差=(2 * N + 2 * D)–(2 * N + D)=D。

C++
// CPP code to generate numbers
// with difference between
// product and sum is D
#include 
using namespace std;
 
// Function to implement calculation
void findNumbers(int n, int d)
{
    for (int i = 0; i < n - 2; i++)
        cout << "1"  << " ";
 
    cout << "2" << " ";
    cout << n + d << endl;
}
 
// Driver code
int main()
{
    int N = 3, D = 5;
    findNumbers(N, D);
    return 0;
}


Java
// Java code to generate numbers
// with difference between
// product and sum is D
import java.io.*;
 
class GFG {
     
    // Function to implement calculation
    static void findNumbers(int n, int d)
    {
        for (int i = 0; i < n - 2; i++)
            System.out.print("1" + " ");
     
        System.out.print("2" + " ");
        System.out.println(n + d);
    }
     
    // Driver code
    public static void main(String args[])
    {
        int N = 3, D = 5;
        findNumbers(N, D);
    }
}
 
/* This code is contributed by Nikita Tiwari.*/


Python3
# Python3 code to generate numbers with
# difference between product and sum is D
 
# Function to implement calculation
def pattern(n, d) :
     
    for i in range(0, n - 2) :
        print("1", end=" ")
         
    print("2", end=" ")
    print(n + d)
 
# Driver code
N = 3
D = 5
pattern(N, D)
 
 
# This code is contributed by 'Akanshgupta'


C#
// C# code to generate numbers
// with difference between
// product and sum is D
using System;
 
class GFG {
     
    // Function to implement calculation
    static void findNumbers(int n, int d)
    {
        for (int i = 0; i < n - 2; i++)
        Console.Write("1" + " ");
     
        Console.Write("2" + " ");
        Console.Write(n + d);
    }
     
    // Driver code
    public static void Main()
    {
        int N = 3, D = 5;
        findNumbers(N, D);
    }
}
 
/* This code is contributed by vt_m.*/


PHP


Javascript


输出 :

1 2 8