热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

数组中出现斐波那契次数的元素的GCD

数组中出现斐波那契次数的元素的 GCD原文:https://www . geesforgeks . org/gcd-of-ele

数组中出现斐波那契次数的元素的 GCD

原文:https://www . geesforgeks . org/gcd-of-elements-occurrent-Fibonacci-数组中的次数/

给定一个包含 N 元素的数组 arr[] ,任务是找到具有频率计数的元素的 GCD ,该频率计数是数组中的斐波那契数。
举例:

输入: arr[] = { 5,3,6,5,6,6,5,5 }
输出: 3
解释:
元素 5,3,6 分别出现 4,1,3 次。
因此,3 和 6 具有斐波那契频率。
所以,gcd(3,6) = 1
输入: arr[] = {4,2,3,3,3,3}
输出: 2
解释:
元素 4,2,3 分别出现 1,1,4 次。
因此,4 和 2 有斐波那契频率。
所以,gcd(4,2) = 2

方法:想法是使用散列来预计算并存储斐波那契节点直到最大值,以使检查变得容易且高效(在 O(1)时间内)。
预计算哈希后:


  1. 遍历数组并将所有元素的频率存储在图中。

  2. 使用映射和散列,使用预先计算的散列计算具有斐波那契频率的元素的 gcd 。

以下是上述方法的实现:

C++

// C++ program to find the GCD of
// elements which occur Fibonacci
// number of times
#include
using namespace std;
// Function to create hash table
// to check Fibonacci numbers
void createHash(set& hash,
                int maxElement)
{
    // Inserting the first two
    // numbers into the hash
    int prev = 0, curr = 1;
    hash.insert(prev);
    hash.insert(curr);
    // Adding the remaining Fibonacci
    // numbers using the previously
    // added elements
    while (curr <= maxElement) {
        int temp = curr + prev;
        hash.insert(temp);
        prev = curr;
        curr = temp;
    }
}
// Function to return the GCD of elements
// in an array having fibonacci frequency
int gcdFibonacciFreq(int arr[], int n)
{
    set hash;
    // Creating the hash
    createHash(hash,
               *max_element(arr,
                            arr + n));
    int i, j;
    // Map is used to store the
    // frequencies of the elements
    unordered_map m;
    // Iterating through the array
    for (i = 0; i         m[arr[i]]++;
    int gcd = 0;
    // Traverse the map using iterators
    for (auto it = m.begin();
         it != m.end(); it++) {
        // Calculate the gcd of elements
        // having fibonacci frequencies
        if (hash.find(it->second)
            != hash.end()) {
            gcd = __gcd(gcd,
                        it->first);
        }
    }
    return gcd;
}
// Driver code
int main()
{
    int arr[] = { 5, 3, 6, 5,
                  6, 6, 5, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout <    return 0;
}

Java 语言(一种计算机语言,尤用于创建网站)

// Java program to find the GCD of
// elements which occur Fibonacci
// number of times
import java.util.*;
class GFG{
// Function to create hash table
// to check Fibonacci numbers
static void createHash(HashSet hash,
                int maxElement)
{
    // Inserting the first two
    // numbers into the hash
    int prev = 0, curr = 1;
    hash.add(prev);
    hash.add(curr);
    // Adding the remaining Fibonacci
    // numbers using the previously
    // added elements
    while (curr <= maxElement) {
        int temp = curr + prev;
        hash.add(temp);
        prev = curr;
        curr = temp;
    }
}
// Function to return the GCD of elements
// in an array having fibonacci frequency
static int gcdFibonacciFreq(int arr[], int n)
{
    HashSet hash = new HashSet();
    // Creating the hash
    createHash(hash,Arrays.stream(arr).max().getAsInt());
    int i;
    // Map is used to store the
    // frequencies of the elements
    HashMap m = new HashMap();
    // Iterating through the array
    for (i = 0; i         if(m.containsKey(arr[i])){
            m.put(arr[i], m.get(arr[i])+1);
        }
        else{
            m.put(arr[i], 1);
        }
    }
    int gcd = 0;
    // Traverse the map using iterators
    for (Map.Entry it : m.entrySet()) {
        // Calculate the gcd of elements
        // having fibonacci frequencies
        if (hash.contains(it.getValue())) {
            gcd = __gcd(gcd,
                        it.getKey());
        }
    }
    return gcd;
}
static int __gcd(int a, int b) 

    return b == 0? a:__gcd(b, a % b);    
}
// Driver code
public static void main(String[] args)
{
    int arr[] = { 5, 3, 6, 5,
                  6, 6, 5, 5 };
    int n = arr.length;
    System.out.print(gcdFibonacciFreq(arr, n));
}
}
// This code is contributed by Princi Singh

Python 3

# Python 3 program to find the GCD of
# elements which occur Fibonacci
# number of times
from collections import defaultdict
import math
# Function to create hash table
# to check Fibonacci numbers
def createHash(hash1,maxElement):
    # Inserting the first two
    # numbers into the hash
    prev , curr = 0, 1
    hash1.add(prev)
    hash1.add(curr)
    # Adding the remaining Fibonacci
    # numbers using the previously
    # added elements
    while (curr <= maxElement):
        temp = curr + prev
        if temp <= maxElement:
            hash1.add(temp)
        prev = curr
        curr = temp
# Function to return the GCD of elements
# in an array having fibonacci frequency
def gcdFibonacciFreq(arr, n):
    hash1 = set()
    # Creating the hash
    createHash(hash1,max(arr))
    # Map is used to store the
    # frequencies of the elements
    m = defaultdict(int)
    # Iterating through the array
    for i in range(n):
        m[arr[i]] += 1
    gcd = 0
    # Traverse the map using iterators
    for it in m.keys():
        # Calculate the gcd of elements
        # having fibonacci frequencies
        if (m[it] in hash1):
            gcd = math.gcd(gcd,it)
    return gcd
# Driver code
if __name__ == "__main__":
    arr = [ 5, 3, 6, 5,
                  6, 6, 5, 5 ]
    n = len(arr)
    print(gcdFibonacciFreq(arr, n))
 # This code is contributed by chitranayal

C

// C# program to find the GCD of
// elements which occur Fibonacci
// number of times
using System;
using System.Linq;
using System.Collections.Generic;
class GFG{
// Function to create hash table
// to check Fibonacci numbers
static void createHash(HashSet hash,
                int maxElement)
{
    // Inserting the first two
    // numbers into the hash
    int prev = 0, curr = 1;
    hash.Add(prev);
    hash.Add(curr);
    // Adding the remaining Fibonacci
    // numbers using the previously
    // added elements
    while (curr <= maxElement) {
        int temp = curr + prev;
        hash.Add(temp);
        prev = curr;
        curr = temp;
    }
}
// Function to return the GCD of elements
// in an array having fibonacci frequency
static int gcdFibonacciFreq(int []arr, int n)
{
    HashSet hash = new HashSet();
    // Creating the hash
    createHash(hash, hash.Count > 0 ? hash.Max():0);
    int i;
    // Map is used to store the
    // frequencies of the elements
    Dictionary m = new Dictionary();
    // Iterating through the array
    for (i = 0; i         if(m.ContainsKey(arr[i])){
            m[arr[i]] = m[arr[i]] + 1;
        }
        else{
            m.Add(arr[i], 1);
        }
    }
    int gcd = 0;
    // Traverse the map using iterators
    foreach(KeyValuePair it in m) {
        // Calculate the gcd of elements
        // having fibonacci frequencies
        if (hash.Contains(it.Value)) {
            gcd = __gcd(gcd,
                        it.Key);
        }
    }
    return gcd;
}
static int __gcd(int a, int b) 

    return b == 0? a:__gcd(b, a % b);    
}
// Driver code
public static void Main(String[] args)
{
    int []arr = { 5, 3, 6, 5,
                  6, 6, 5, 5 };
    int n = arr.Length;
    Console.Write(gcdFibonacciFreq(arr, n));
}
}
// This code is contributed by 29AjayKumar

java 描述语言


Output: 

3

时间复杂度:0(N)

辅助空间:O(N)


推荐阅读
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文介绍了P1651题目的描述和要求,以及计算能搭建的塔的最大高度的方法。通过动态规划和状压技术,将问题转化为求解差值的问题,并定义了相应的状态。最终得出了计算最大高度的解法。 ... [详细]
  • 展开全部下面的代码是创建一个立方体Thisexamplescreatesanddisplaysasimplebox.#Thefirstlineloadstheinit_disp ... [详细]
  • C++字符字符串处理及字符集编码方案
    本文介绍了C++中字符字符串处理的问题,并详细解释了字符集编码方案,包括UNICODE、Windows apps采用的UTF-16编码、ASCII、SBCS和DBCS编码方案。同时说明了ANSI C标准和Windows中的字符/字符串数据类型实现。文章还提到了在编译时需要定义UNICODE宏以支持unicode编码,否则将使用windows code page编译。最后,给出了相关的头文件和数据类型定义。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文介绍了一个Java猜拳小游戏的代码,通过使用Scanner类获取用户输入的拳的数字,并随机生成计算机的拳,然后判断胜负。该游戏可以选择剪刀、石头、布三种拳,通过比较两者的拳来决定胜负。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
  • 本文介绍了一种划分和计数油田地块的方法。根据给定的条件,通过遍历和DFS算法,将符合条件的地块标记为不符合条件的地块,并进行计数。同时,还介绍了如何判断点是否在给定范围内的方法。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 从零学Java(10)之方法详解,喷打野你真的没我6!
    本文介绍了从零学Java系列中的第10篇文章,详解了Java中的方法。同时讨论了打野过程中喷打野的影响,以及金色打野刀对经济的增加和线上队友经济的影响。指出喷打野会导致线上经济的消减和影响队伍的团结。 ... [详细]
author-avatar
是不是有谁代替我陪在你身旁
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有