📌  相关文章
📜  检查是否存在长度K与总和等于阶乘的子数组

📅  最后修改于: 2021-05-17 16:41:23             🧑  作者: Mango

给定N个整数和整数K的数组arr [] 任务是找到一个长度为K的子数组,该数组的元素之和等于任意数量的阶乘。如果不存在这样的子数组,则打印“ -1”

例子:

天真的方法:解决该问题的最简单方法是计算所有长度为K的子数组的和,并检查这些和中的任何一个是否为任意数量的阶乘。如果发现对于任何子数组为true,则打印该子数组。否则,打印“ -1”
时间复杂度: O(N * K)
辅助空间: O(1)

高效方法:为优化上述方法,其思想是使用滑动窗口技术计算长度为K的所有子数组的总和,然后检查总和是否为阶乘。步骤如下:

  1. 计算前K个数组元素的总和,并将总和存储在变量中,例如sum
  2. 然后遍历剩余的数组,并通过从先前的子数组中减去第一个元素并添加当前的数组元素,不断更新sum以获得大小为K的当前子数组的总和。
  3. 要检查总和是否是一个阶乘,请将该总和除以2、3,以此类推,直到无法再对其求和。如果数字减少为1,则总和是数字的阶乘。
  4. 如果以上步骤中的总和是一个数字的阶乘,则存储该子数组的开始和结束索引以打印该子数组。
  5. 完成上述步骤后,如果找不到此类子数组,请打印“ -1” 。否则,打印存储开始索引和结束索引的子数组。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if a number
// is factorial of a number or not
int isFactorial(int n)
{
    int i = 2;
    while (n != 1) {
 
        // If n is not a factorial
        if (n % i != 0) {
            return 0;
        }
        n /= i;
        i++;
    }
    return i - 1;
}
 
// Function to return the index of
// the valid subarray
pair sumFactorial(
    vector arr, int K)
{
    int i, sum = 0, ans;
 
    // Calaculate the sum of
    // first subarray of length K
    for (i = 0; i < K; i++) {
 
        sum += arr[i];
    }
 
    // Check if sum is a factorial
    // of any number or not
    ans = isFactorial(sum);
 
    // If sum of first K length subarray
    // is factorial of a number
    if (ans != 0) {
        return make_pair(ans, 0);
    }
 
    // Find the number formed from the
    // subarray which is a factorial
    for (int j = i; j < arr.size(); j++) {
 
        // Update sum of current subarray
        sum += arr[j] - arr[j - K];
 
        // Check if sum is a factorial
        // of any number or not
        ans = isFactorial(sum);
 
        // If ans is true, then return
        // index of the current subarray
        if (ans != 0) {
            return make_pair(ans,
                             j - K + 1);
        }
    }
 
    // If the required subarray is
    // not possible
    return make_pair(-1, 0);
}
 
// Function to print the subarray whose
// sum is a factorial of any number
void printRes(pair answer,
              vector arr, int K)
{
 
    // If no such subarray exists
    if (answer.first == -1) {
 
        cout << -1 << endl;
    }
 
    // Otherwise
    else {
 
        int i = 0;
        int j = answer.second;
 
        // Iterate to print subarray
        while (i < K) {
 
            cout << arr[j] << " ";
            i++;
            j++;
        }
    }
}
 
// Driver Code
int main()
{
    vector arr
        = { 23, 45, 2, 4,
            6, 9, 3, 32 };
 
    // Given sum K
    int K = 5;
 
    // Function Call
    pair answer
        = sumFactorial(arr, K);
 
    // Print the result
    printRes(answer, arr, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
import java.io.*;
 
class GFG{
     
// Pair class
public static class Pair
{
    int x;
    int y;
     
    Pair(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}
 
// Function to check if a number
// is factorial of a number or not
static int isFactorial(int n)
{
    int i = 2;
    while (n != 1)
    {
 
        // If n is not a factorial
        if (n % i != 0)
        {
            return 0;
        }
        n /= i;
        i++;
    }
    return i - 1;
}
 
// Function to return the index of
// the valid subarray
static ArrayList sumFactorial(int arr[],
                                    int K)
{
    ArrayList pair = new ArrayList<>();
     
    int i, sum = 0, ans;
 
    // Calaculate the sum of
    // first subarray of length K
    for(i = 0; i < K; i++)
    {
        sum += arr[i];
    }
     
    // Check if sum is a factorial
    // of any number or not
    ans = isFactorial(sum);
     
    // If sum of first K length subarray
    // is factorial of a number
    if (ans != 0)
    {
        Pair p = new Pair(ans, 0);
        pair.add(p);
        return pair;
    }
 
    // Find the number formed from the
    // subarray which is a factorial
    for(int j = i; j < arr.length; j++)
    {
 
        // Update sum of current subarray
        sum += arr[j] - arr[j - K];
 
        // Check if sum is a factorial
        // of any number or not
        ans = isFactorial(sum);
 
        // If ans is true, then return
        // index of the current subarray
        if (ans != 0)
        {
            Pair p = new Pair(ans, j - K + 1);
            pair.add(p);
            return pair;
        }
    }
 
    // If the required subarray is
    // not possible
    Pair p = new Pair(-1, 0);
    pair.add(p);
    return pair;
}
 
// Function to print the subarray whose
// sum is a factorial of any number
static void printRes(ArrayList answer,
                     int arr[], int K)
{
     
    // If no such subarray exists
    if (answer.get(0).x == -1)
    {
         
        // cout << -1 << endl;
        System.out.println("-1");
    }
 
    // Otherwise
    else
    {
        int i = 0;
        int j = answer.get(0).y;
 
        // Iterate to print subarray
        while (i < K)
        {
            System.out.print(arr[j] + " ");
            i++;
            j++;
        }
    }
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given array arr[] and brr[]
    int arr[] = { 23, 45, 2, 4,
                  6, 9, 3, 32 };
                   
    int K = 5;
    ArrayList answer = new ArrayList<>();
     
    // Function call
    answer = sumFactorial(arr,K);
                     
    // Print the result
    printRes(answer, arr, K);
}
}
 
// This code is contributed by bikram2001jha


Python3
# Python3 program for the above approach
 
# Function to check if a number
# is factorial of a number or not
def isFactorial(n):
 
    i = 2
     
    while (n != 1):
         
        # If n is not a factorial
        if (n % i != 0):
            return 0
         
        n = n // i
        i += 1
     
    return i - 1
 
# Function to return the index of
# the valid subarray
def sumFactorial(arr, K):
 
    i, Sum = 0, 0
 
    # Calaculate the sum of
    # first subarray of length K
    while(i < K):
        Sum += arr[i]
        i += 1
 
    # Check if sum is a factorial
    # of any number or not
    ans = isFactorial(Sum)
 
    # If sum of first K length subarray
    # is factorial of a number
    if (ans != 0):
        return (ans, 0)
 
    # Find the number formed from the
    # subarray which is a factorial
    for j in range(i, len(arr)):
     
        # Update sum of current subarray
        Sum = Sum + arr[j] - arr[j - K]
 
        # Check if sum is a factorial
        # of any number or not
        ans = isFactorial(Sum)
 
        # If ans is true, then return
        # index of the current subarray
        if (ans != 0):
            return (ans, j - K + 1)
 
    # If the required subarray is
    # not possible
    return (-1, 0)
 
# Function to print the subarray whose
# sum is a factorial of any number
def printRes(answer, arr, K):
 
    # If no such subarray exists
    if (answer[0] == -1):
        print(-1)
 
    # Otherwise
    else:
        i = 0
        j = answer[1]
 
        # Iterate to print subarray
        while (i < K):
            print(arr[j], end = " ")
            i += 1
            j += 1
 
# Driver code
arr = [ 23, 45, 2, 4, 6, 9, 3, 32 ]
 
# Given sum K
K = 5
 
# Function call
answer = sumFactorial(arr, K)
 
# Print the result
printRes(answer, arr, K)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
// Pair class
public class Pair
{
  public int x;
  public int y;
 
  public Pair(int x, int y)
  {
    this.x = x;
    this.y = y;
  }
}
 
// Function to check if a number
// is factorial of a number or not
static int isFactorial(int n)
{
  int i = 2;
  while (n != 1)
  {
    // If n is not
    // a factorial
    if (n % i != 0)
    {
      return 0;
    }
    n /= i;
    i++;
  }
  return i - 1;
}
 
// Function to return the index of
// the valid subarray
static List sumFactorial(int []arr,
                               int K)
{
  List pair = new List();
  int i, sum = 0, ans;
 
  // Calaculate the sum of
  // first subarray of length K
  for(i = 0; i < K; i++)
  {
    sum += arr[i];
  }
 
  // Check if sum is a factorial
  // of any number or not
  ans = isFactorial(sum);
 
  // If sum of first K length subarray
  // is factorial of a number
  if (ans != 0)
  {
    Pair p = new Pair(ans, 0);
    pair.Add(p);
    return pair;
  }
 
  // Find the number formed from the
  // subarray which is a factorial
  for(int j = i; j < arr.Length; j++)
  {
    // Update sum of current subarray
    sum += arr[j] - arr[j - K];
 
    // Check if sum is a factorial
    // of any number or not
    ans = isFactorial(sum);
 
    // If ans is true, then return
    // index of the current subarray
    if (ans != 0)
    {
      Pair p = new Pair(ans, j - K + 1);
      pair.Add(p);
      return pair;
    }
  }
 
  // If the required subarray is
  // not possible
  Pair p1 = new Pair(-1, 0);
  pair.Add(p1);
  return pair;
}
 
// Function to print the subarray whose
// sum is a factorial of any number
static void printRes(List answer,
                     int []arr, int K)
{
  // If no such subarray exists
  if (answer[0].x == -1)
  {
    // cout << -1 << endl;
    Console.WriteLine("-1");
  }
 
  // Otherwise
  else
  {
    int i = 0;
    int j = answer[0].y;
 
    // Iterate to print subarray
    while (i < K)
    {
      Console.Write(arr[j] + " ");
      i++;
      j++;
    }
  }
}
 
// Driver Code
public static void Main(String []args)
{    
  // Given array []arr and brr[]
  int []arr = {23, 45, 2, 4,
               6, 9, 3, 32};
  int K = 5;
  List answer = new List();
   
  // Function call
  answer = sumFactorial(arr, K);
 
  // Print the result
  printRes(answer, arr, K);
}
}
 
// This code is contributed by shikhasingrajput


输出:
2 4 6 9 3



时间复杂度: O(N)
辅助空间: O(1)