热门标签 | 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。看到你的文章出现在极客博客主页上,帮助其他极客。
如果发现有不正确的地方,或者想分享更多关于上述话题的信息,请写评论。


推荐阅读
  • 本文探讨了如何在给定整数N的情况下,找到两个不同的整数a和b,使得它们的和最大,并且满足特定的数学条件。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 本文详细介绍了Akka中的BackoffSupervisor机制,探讨其在处理持久化失败和Actor重启时的应用。通过具体示例,展示了如何配置和使用BackoffSupervisor以实现更细粒度的异常处理。 ... [详细]
  • 2023年京东Android面试真题解析与经验分享
    本文由一位拥有6年Android开发经验的工程师撰写,详细解析了京东面试中常见的技术问题。涵盖引用传递、Handler机制、ListView优化、多线程控制及ANR处理等核心知识点。 ... [详细]
  • 本文介绍了如何通过 Maven 依赖引入 SQLiteJDBC 和 HikariCP 包,从而在 Java 应用中高效地连接和操作 SQLite 数据库。文章提供了详细的代码示例,并解释了每个步骤的实现细节。 ... [详细]
  • 本文探讨了《魔兽世界》中红蓝两方阵营在备战阶段的策略与实现方法,通过代码展示了双方如何根据资源和兵种特性进行战士生产。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 本文介绍如何使用阿里云的fastjson库解析包含时间戳、IP地址和参数等信息的JSON格式文本,并进行数据处理和保存。 ... [详细]
  • PHP 5.5.0rc1 发布:深入解析 Zend OPcache
    2013年5月9日,PHP官方发布了PHP 5.5.0rc1和PHP 5.4.15正式版,这两个版本均支持64位环境。本文将详细介绍Zend OPcache的功能及其在Windows环境下的配置与测试。 ... [详细]
  • 尽管使用TensorFlow和PyTorch等成熟框架可以显著降低实现递归神经网络(RNN)的门槛,但对于初学者来说,理解其底层原理至关重要。本文将引导您使用NumPy从头构建一个用于自然语言处理(NLP)的RNN模型。 ... [详细]
  • Java编程实践:深入理解方法重载
    本文介绍了Java中方法重载的概念及其应用。通过多个示例,详细讲解了如何在同一类中定义具有相同名称但不同参数列表的方法,以实现更灵活的功能调用。 ... [详细]
  • 本题通过将每个矩形视为一个节点,根据其相对位置构建拓扑图,并利用深度优先搜索(DFS)或状态压缩动态规划(DP)求解最小涂色次数。本文详细解析了该问题的建模思路与算法实现。 ... [详细]
  • 最近团队在部署DLP,作为一个技术人员对于黑盒看不到的地方还是充满了好奇心。多次咨询乙方人员DLP的算法原理是什么,他们都以商业秘密为由避而不谈,不得已只能自己查资料学习,于是有了下面的浅见。身为甲方,虽然不需要开发DLP产品,但是也有必要弄明白DLP基本的原理。俗话说工欲善其事必先利其器,只有在懂这个工具的原理之后才能更加灵活地使用这个工具,即使出现意外情况也能快速排错,越接近底层,越接近真相。根据DLP的实际用途,本文将DLP检测分为2部分,泄露关键字检测和近似重复文档检测。 ... [详细]
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社区 版权所有