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

寻找一个整数可以表示为唯一自然数的n次方的和的方法

寻找一个整数可以表示为唯一自然数的n次方的和的方法原文:ht

寻找一个整数可以表示为唯一自然数的 n 次方的和的方法

原文:https://www . geesforgeks . org/find-way-integer-can-expressed-sum-n-th-power-unique-natural-numbers/

给定两个数字 x 和 n,找出 x 可以表示为唯一自然数的 n 次幂之和的几种方法。

示例:

输入: x = 10,n = 2
输出: 1
解释: 10 = 1 2 + 3 2 ,因此共有 1 种可能性

输入: x = 100,n = 2
输出: 3
E 解释:
100 = 102OR 62+82OR 12+32+42+52+

想法很简单。我们从 1 开始遍历所有数字。对于每个数字,我们递归地尝试所有更大的数字,如果我们能够找到和,我们增加结果

C++

// C++ program to count number of ways any
// given integer x can be expressed as n-th
// power of unique natural numbers.
#include
using namespace std;
// Function to calculate and return the
// power of any given number
int power(int num, unsigned int n)
{
    if (n == 0)
        return 1;
    else if (n % 2 == 0)
        return power(num, n / 2) * power(num, n / 2);
    else
        return num * power(num, n / 2) * power(num, n / 2);
}
// Function to check power representations recursively
int checkRecursive(int x, int n, int curr_num = 1,
                   int curr_sum = 0)
{
    // Initialize number of ways to express
    // x as n-th powers of different natural
    // numbers
    int results = 0;
    // Calling power of 'i' raised to 'n'
    int p = power(curr_num, n);
    while (p + curr_sum         // Recursively check all greater values of i
        results += checkRecursive(x, n, curr_num + 1,
                                  p + curr_sum);
        curr_num++;
        p = power(curr_num, n);
    }
    // If sum of powers is equal to x
    // then increase the value of result.
    if (p + curr_sum == x)
        results++;
    // Return the final result
    return results;
}
// Driver Code.
int main()
{
    int x = 10, n = 2;
    cout <    return 0;
}

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

// Java program to count number of ways any
// given integer x can be expressed as n-th
// power of unique natural numbers.
class GFG {
    // Function to calculate and return the
    // power of any given number
    static int power(int num, int n)
    {
        if (n == 0)
            return 1;
        else if (n % 2 == 0)
            return power(num, n / 2) * power(num, n / 2);
        else
            return num * power(num, n / 2)
                * power(num, n / 2);
    }
    // Function to check power representations recursively
    static int checkRecursive(int x, int n, int curr_num,
                              int curr_sum)
    {
        // Initialize number of ways to express
        // x as n-th powers of different natural
        // numbers
        int results = 0;
        // Calling power of 'i' raised to 'n'
        int p = power(curr_num, n);
        while (p + curr_sum             // Recursively check all greater values of i
            results += checkRecursive(x, n, curr_num + 1,
                                      p + curr_sum);
            curr_num++;
            p = power(curr_num, n);
        }
        // If sum of powers is equal to x
        // then increase the value of result.
        if (p + curr_sum == x)
            results++;
        // Return the final result
        return results;
    }
    // Driver Code.
    public static void main(String[] args)
    {
        int x = 10, n = 2;
        System.out.println(checkRecursive(x, n, 1, 0));
    }
}
// This code is contributed by mits

计算机编程语言

# Python3 program to count number of ways any
# given integer x can be expressed as n-th
# power of unique natural numbers.
# Function to calculate and return the
# power of any given number
def power(num, n):
    if(n == 0):
        return 1
    elif(n % 2 == 0):
        return power(num, n // 2) * power(num, n // 2)
    else:
        return num * power(num, n // 2) * power(num, n // 2)
# Function to check power representations recursively
def checkRecursive(x, n, curr_num=1, curr_sum=0):
    # Initialize number of ways to express
    # x as n-th powers of different natural
    # numbers
    results = 0
    # Calling power of 'i' raised to 'n'
    p = power(curr_num, n)
    while(p + curr_sum         # Recursively check all greater values of i
        results += checkRecursive(x, n, curr_num + 1, p + curr_sum)
        curr_num = curr_num + 1
        p = power(curr_num, n)
    # If sum of powers is equal to x
    # then increase the value of result.
    if(p + curr_sum == x):
        results = results + 1
    # Return the final result
    return results
# Driver Code.
if __name__ == '__main__':
    x = 10
    n = 2
    print(checkRecursive(x, n))
# This code is contributed by
# Sanjit_Prasad

C

// C# program to count number of ways any
// given integer x can be expressed as
// n-th power of unique natural numbers.
using System;
class GFG {
    // Function to calculate and return
    // the power of any given number
    static int power(int num, int n)
    {
        if (n == 0)
            return 1;
        else if (n % 2 == 0)
            return power(num, n / 2) * power(num, n / 2);
        else
            return num * power(num, n / 2)
                * power(num, n / 2);
    }
    // Function to check power
    // representations recursively
    static int checkRecursive(int x, int n, int curr_num,
                              int curr_sum)
    {
        // Initialize number of ways to express
        // x as n-th powers of different natural
        // numbers
        int results = 0;
        // Calling power of 'i' raised to 'n'
        int p = power(curr_num, n);
        while (p + curr_sum             // Recursively check all greater values of i
            results += checkRecursive(x, n, curr_num + 1,
                                      p + curr_sum);
            curr_num++;
            p = power(curr_num, n);
        }
        // If sum of powers is equal to x
        // then increase the value of result.
        if (p + curr_sum == x)
            results++;
        // Return the final result
        return results;
    }
    // Driver Code.
    public static void Main()
    {
        int x = 10, n = 2;
        System.Console.WriteLine(
            checkRecursive(x, n, 1, 0));
    }
}
// This code is contributed by mits

服务器端编程语言(Professional Hypertext Preprocessor 的缩写)

// PHP program to count
// number of ways any
// given integer x can
// be expressed as n-th
// power of unique
// natural numbers.
// Function to calculate and return
// the power of any given number
function power($num, $n)
{
    if ($n == 0)
        return 1;
    else if ($n % 2 == 0)
        return power($num, (int)($n / 2)) *
               power($num, (int)($n / 2));
    else
        return $num * power($num, (int)($n / 2)) *
                      power($num, (int)($n / 2));
}
// Function to check power
// representations recursively
function checkRecursive($x, $n,
                        $curr_num = 1,
                        $curr_sum = 0)
{
    // Initialize number of
    // ways to express
    // x as n-th powers
    // of different natural
    // numbers
    $results = 0;
    // Calling power of 'i'
    // raised to 'n'
    $p = power($curr_num, $n);
    while ($p + $curr_sum <$x)
    {
        // Recursively check all
        // greater values of i
        $results += checkRecursive($x, $n,
                                   $curr_num + 1,
                                   $p + $curr_sum);
        $curr_num++;
        $p = power($curr_num, $n);
    }
    // If sum of powers
    // is equal to x
    // then increase the
    // value of result.
    if ($p + $curr_sum == $x)
        $results++;
    // Return the final result
    return $results;
}
// Driver Code.
$x = 10; $n = 2;
echo(checkRecursive($x, $n));
// This code is contributed by Ajit.
?>

java 描述语言


Output

1

备选方案:

以下是由 Shivam Kanodia 提供的另一个更简单的解决方案。

C++

// C++ program to find number of ways to express
// a number as sum of n-th powers of numbers.
#include
using namespace std;
int res = 0;
int checkRecursive(int num, int x, int k, int n)
{
    if (x == 0)
        res++;
    int r = (int)floor(pow(num, 1.0 / n));
    for (int i = k + 1; i <= r; i++)
    {
        int a = x - (int)pow(i, n);
        if (a >= 0)
            checkRecursive(num, x -
                          (int)pow(i, n), i, n);
    }
    return res;
}
// Wrapper over checkRecursive()
int check(int x, int n)
{
    return checkRecursive(x, x, 0, n);
}
// Driver Code
int main()
{
    cout <<(check(10, 2));
    return 0;
}
// This code is contributed by mits

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

// Java program to find number of ways to express a
// number as sum of n-th powers of numbers.
import java.io.*;
import java.util.*;
public class Solution {
    static int res = 0;
    static int checkRecursive(int num, int x, int k, int n)
    {
        if (x == 0)
            res++;
        int r = (int)Math.floor(Math.pow(num, 1.0 / n));
        for (int i = k + 1; i <= r; i++) {
            int a = x - (int)Math.pow(i, n);
          if (a >= 0)
            checkRecursive(num,
                   x - (int)Math.pow(i, n), i, n);
        }
        return res;
    }
    // Wrapper over checkRecursive()
    static int check(int x, int n)
    {
        return checkRecursive(x, x, 0, n);
    }
    public static void main(String[] args)
    {
        System.out.println(check(10, 2));
    }
}

Python 3

# Python 3 program to find number of ways to express
# a number as sum of n-th powers of numbers.
def checkRecursive(num, rem_num, next_int, n, ans=0):
    if (rem_num == 0):
        ans += 1
    r = int(num**(1 / n))
    for i in range(next_int + 1, r + 1):
        a = rem_num - int(i**n)
        if a >= 0:
            ans += checkRecursive(num, rem_num - int(i**n), i, n, 0)
    return ans
# Wrapper over checkRecursive()
def check(x, n):
    return checkRecursive(x, x, 0, n)
# Driver Code
if __name__ == '__main__':
    print(check(10, 2))
# This code is contributed by
# Surendra_Gangwar

C

// C# program to find number of
// ways to express a number as sum
// of n-th powers of numbers.
using System;
class Solution {
    static int res = 0;
    static int checkRecursive(int num, int x,
                                int k, int n)
    {
        if (x == 0)
            res++;
        int r = (int)Math.Floor(Math.Pow(num, 1.0 / n));
        for (int i = k + 1; i <= r; i++)
        {
            int a = x - (int)Math.Pow(i, n);
        if (a >= 0)
            checkRecursive(num, x -
                          (int)Math.Pow(i, n), i, n);
        }
        return res;
    }
    // Wrapper over checkRecursive()
    static int check(int x, int n)
    {
        return checkRecursive(x, x, 0, n);
    }
    // Driver code
    public static void Main()
    {
        Console.WriteLine(check(10, 2));
    }
}
// This code is contributed by vt_m.

服务器端编程语言(Professional Hypertext Preprocessor 的缩写)

// PHP program to find number
// of ways to express a number
// as sum of n-th powers of numbers.
$res = 0;
function checkRecursive($num, $x,
                        $k, $n)
{
    global $res;
    if ($x == 0)
        $res++;
    $r = (int)floor(pow($num,
                        1.0 / $n));
    for ($i = $k + 1;
         $i <= $r; $i++)
    {
        $a = $x - (int)pow($i, $n);
        if ($a >= 0)
            checkRecursive($num, $x -
                    (int)pow($i, $n),
                             $i, $n);
    }
    return $res;
}
// Wrapper over
// checkRecursive()
function check($x, $n)
{
    return checkRecursive($x, $x,
                          0, $n);
}
// Driver Code
echo (check(10, 2));
// This code is contributed by ajit
?>

java 描述语言


Output

1

简单递归解:

拉姆·琼达尔T4 贡献。

C++

#include
#include
using namespace std;
//Helper function
int getAllWaysHelper(int remainingSum, int power, int base){
      //calculate power
    int result = pow(base, power);
    if(remainingSum == result)
        return 1;
    if(remainingSum         return 0;
      //Two recursive calls one to include current base's power in sum another to exclude
    int x = getAllWaysHelper(remainingSum - result, power, base + 1);
    int y = getAllWaysHelper(remainingSum, power, base+1);
    return x + y;
}
int getAllWays(int sum, int power) {
    return getAllWaysHelper(sum, power, 1);
}
// Driver Code.
int main()
{
    int x = 10, n = 2;
    cout <    return 0;
}

Output

1

本文由 丹麦 KALEEM 供稿。如果你喜欢 GeeksforGeeks 并想投稿,你也可以使用write.geeksforgeeks.org写一篇文章或者把你的文章邮寄到 review-team@geeksforgeeks.org。看到你的文章出现在极客博客主页上,帮助其他极客。
如果发现有不正确的地方,或者想分享更多关于上述话题的信息,请写评论。


推荐阅读
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • C# 7.0 新特性:基于Tuple的“多”返回值方法
    本文介绍了C# 7.0中基于Tuple的“多”返回值方法的使用。通过对C# 6.0及更早版本的做法进行回顾,提出了问题:如何使一个方法可返回多个返回值。然后详细介绍了C# 7.0中使用Tuple的写法,并给出了示例代码。最后,总结了该新特性的优点。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • Java中包装类的设计原因以及操作方法
    本文主要介绍了Java中设计包装类的原因以及操作方法。在Java中,除了对象类型,还有八大基本类型,为了将基本类型转换成对象,Java引入了包装类。文章通过介绍包装类的定义和实现,解答了为什么需要包装类的问题,并提供了简单易用的操作方法。通过本文的学习,读者可以更好地理解和应用Java中的包装类。 ... [详细]
  • 本文介绍了Java中Hashtable的clear()方法,该方法用于清除和移除指定Hashtable中的所有键。通过示例程序演示了clear()方法的使用。 ... [详细]
  • 本文由编程笔记#小编整理,主要介绍了关于数论相关的知识,包括数论的算法和百度百科的链接。文章还介绍了欧几里得算法、辗转相除法、gcd、lcm和扩展欧几里得算法的使用方法。此外,文章还提到了数论在求解不定方程、模线性方程和乘法逆元方面的应用。摘要长度:184字。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 本文介绍了P1651题目的描述和要求,以及计算能搭建的塔的最大高度的方法。通过动态规划和状压技术,将问题转化为求解差值的问题,并定义了相应的状态。最终得出了计算最大高度的解法。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • 本文介绍了Windows操作系统的版本及其特点,包括Windows 7系统的6个版本:Starter、Home Basic、Home Premium、Professional、Enterprise、Ultimate。Windows操作系统是微软公司研发的一套操作系统,具有人机操作性优异、支持的应用软件较多、对硬件支持良好等优点。Windows 7 Starter是功能最少的版本,缺乏Aero特效功能,没有64位支持,最初设计不能同时运行三个以上应用程序。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
author-avatar
8prye孙瑞D
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有