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


推荐阅读
  • 本题探讨了在一个有向图中,如何根据特定规则将城市划分为若干个区域,使得每个区域内的城市之间能够相互到达,并且划分的区域数量最少。题目提供了时间限制和内存限制,要求在给定的城市和道路信息下,计算出最少需要划分的区域数量。 ... [详细]
  • 编程挑战:2019 Nitacm 校赛 D 题 - 雷顿女士与分队(高级版)
    本文深入解析了2019年Nitacm校赛D题——雷顿女士与分队(高级版),详细介绍了问题背景、解题思路及优化方案。 ... [详细]
  • 作为一名 Ember.js 新手,了解如何在路由和模型中正确加载 JSON 数据是至关重要的。本文将探讨两者之间的差异,并提供实用的建议。 ... [详细]
  • 本文深入探讨了HTTP请求和响应对象的使用,详细介绍了如何通过响应对象向客户端发送数据、处理中文乱码问题以及常见的HTTP状态码。此外,还涵盖了文件下载、请求重定向、请求转发等高级功能。 ... [详细]
  • 本文详细介绍了C++中map容器的多种删除和交换操作,包括clear、erase、swap、extract和merge方法,并提供了完整的代码示例。 ... [详细]
  • MySQL DateTime 类型数据处理及.0 尾数去除方法
    本文介绍如何在 MySQL 中处理 DateTime 类型的数据,并解决获取数据时出现的.0尾数问题。同时,探讨了不同场景下的解决方案,确保数据格式的一致性和准确性。 ... [详细]
  • 嵌入式系统开发:外部中断详解
    本文深入探讨了外部中断的原理和应用,详细介绍了如何配置和使用外部中断,包括硬件设计、编程实现及调试技巧。 ... [详细]
  • C# LiNQ 查询 join连接
    C# LiNQ 查询 join连接 ... [详细]
  • Java 中的月减()方法 ... [详细]
  • FinOps 与 Serverless 的结合:破解云成本难题
    本文探讨了如何通过 FinOps 实践优化 Serverless 应用的成本管理,提出了首个 Serverless 函数总成本估计模型,并分享了多种有效的成本优化策略。 ... [详细]
  • 本文详细介绍了 iBatis.NET 中的 Iterate 元素,它用于遍历集合并重复生成每个项目的主体内容。通过该元素,可以实现类似于 foreach 的功能,尽管 iBatis.NET 并未直接提供 foreach 标签。 ... [详细]
  • 配置多VLAN环境下的透明SQUID代理
    本文介绍如何在包含多个VLAN的网络环境中配置SQUID作为透明网关。网络拓扑包括Cisco 3750交换机、PANABIT防火墙和SQUID服务器,所有设备均部署在ESXi虚拟化平台上。 ... [详细]
  • 深入解析Redis内存对象模型
    本文详细介绍了Redis内存对象模型的关键知识点,包括内存统计、内存分配、数据存储细节及优化策略。通过实际案例和专业分析,帮助读者全面理解Redis内存管理机制。 ... [详细]
  • 反向投影技术主要用于在大型输入图像中定位特定的小型模板图像。通过直方图对比,它能够识别出最匹配的区域或点,从而确定模板图像在输入图像中的位置。 ... [详细]
  • 本文详细介绍了如何在C#程序运行期间防止系统进入休眠模式以及显示器关闭,提供了具体的实现代码示例,并解释了其应用场景。这不仅有助于提高程序的稳定性,还能优化能源管理。适合需要处理长时间任务(如下载或批处理)的开发者参考。 ... [详细]
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社区 版权所有