The Power Sum, a recursive problem by HackerRank
Another one by HackerRank: https://www.hackerrank.com/challenges/the-power-sum:
Solution is a recursive one where we're varying the number being tested, always ensuring to increment it after adding it up to the current sum, and using as a halting criteria when the current sum surpasses the target sum. Code is down below, cheers, Marcelo.
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
int x = Int32.Parse(Console.ReadLine());
int n = Int32.Parse(Console.ReadLine());
int solutions = 0;
Process(0, x, 1, n, ref solutions);
Console.WriteLine(solutions);
}
static void Process(int currentSum, int targetSum, int currentNumber, int n, ref int solutions)
{
if (currentSum == targetSum)
{
solutions++;
return;
}
for (int i = currentNumber; currentSum + (int)Math.Pow(i, n) <= targetSum; i++)
Process(currentSum + (int)Math.Pow(i, n), targetSum, i + 1, n, ref solutions);
}
}
Find the number of ways that a given integer, , can be expressed as the sum of the power of unique, natural numbers.
Input Format
The first line contains an integer .
The second line contains an integer .
The second line contains an integer .
Constraints
Output Format
Output a single integer, the answer to the problem explained above.
Sample Input 0
10
2
Sample Output 0
1
Explanation 0
If and , we need to find the number of ways that can be represented as the sum of squares of unique numbers.
This is the only way in which can be expressed as the sum of unique squares.
Sample Input 1
100
2
Sample Output 1
3
Explanation 1
Sample Input 2
100
3
Sample Output 2
1
Explanation 2
can be expressed as the sum of the cubes of .
. There is no other way to express as the sum of cubes.
. There is no other way to express as the sum of cubes.
Solution is a recursive one where we're varying the number being tested, always ensuring to increment it after adding it up to the current sum, and using as a halting criteria when the current sum surpasses the target sum. Code is down below, cheers, Marcelo.
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
int x = Int32.Parse(Console.ReadLine());
int n = Int32.Parse(Console.ReadLine());
int solutions = 0;
Process(0, x, 1, n, ref solutions);
Console.WriteLine(solutions);
}
static void Process(int currentSum, int targetSum, int currentNumber, int n, ref int solutions)
{
if (currentSum == targetSum)
{
solutions++;
return;
}
for (int i = currentNumber; currentSum + (int)Math.Pow(i, n) <= targetSum; i++)
Process(currentSum + (int)Math.Pow(i, n), targetSum, i + 1, n, ref solutions);
}
}
Very nice Marcelo! Just discovered your blog thanks Tony interview about Quicksort! Added to my Feedly!
ReplyDeletevery neat, Marcelo! My solution is almost identical :)
ReplyDeletehttp://ideone.com/gxDICb
#include
#include
using namespace std;
int number_of_ways(int target, int power, int start) {
if (target == 0) return 1;
int total = 0;
for (int j = start + 1; pow(j, power) <= target; ++j) {
total += number_of_ways(target-pow(j, power), power, j);
}
return total;
}
int main() {
int x, n; cin >> x >> n;
cout << number_of_ways(x, n, 0);
return 0;
}
can u please explain the code
DeleteHi, I have one question.. If you are using recursion,why you have used loop inside function?
ReplyDeleteRecursion is not free, since, unless function is tail-recursive and compiler knows how to optimize it into iterative implementation, a stack has to be maintained. It's better to use recursion only where it feels natural by directly modeling the algorithm, and iterative computations are usually more natural and shorter when written with plain loops.
DeleteYour blog is very nice,Thanks for sharing good blog.
ReplyDeleteซอมบี้
Nice initiative. Keep doing the good work. csmonk
ReplyDeleteWhen it comes to hosting prices in India, there are options to suit various needs and budgets. Shared hosting plans start at an affordable ₹99 per month, ideal for small websites and blogs. For businesses requiring more resources, VPS hosting begins around ₹499 per month, providing better performance and scalability. Dedicated hosting, offering the highest level of control and performance, starts at approximately ₹4,999 per month. Many hosting providers include added benefits such as free domain registration, SSL certificates, and 24/7 customer support. By comparing different plans and providers, businesses can find the perfect hosting solution to meet their specific needs and budgets.
ReplyDeletehttps://onohosting.com/
Nursing jobs in Australia provide Indian nurses with a wide array of professional opportunities in settings such as hospitals, aged care facilities, and community health centres. Australian healthcare employers value the skills and expertise of Indian nurses, offering positions in specialized areas like intensive care, paediatrics, mental health, and emergency medicine. The high demand for nurses due to an aging population ensures steady job prospects. Indian nurses benefit from competitive salaries, excellent working conditions, and ample chances for career development. Australia’s welcoming, multicultural environment facilitates a smooth transition and integration into the community. Overall, the nursing sector in Australia promises a rewarding career for Indian nurses.
ReplyDeletehttps://dynamichealthstaff.com/nursing-jobs-in-australia-for-indian-nurses
Breast cancer treatment prices in Delhi vary based on several factors such as the type of treatment, stage of cancer, and the healthcare facility. Surgical procedures like a lumpectomy or mastectomy generally cost between INR 1,00,000 and INR 3,00,000. If additional treatments, such as chemotherapy or radiation therapy, are required, costs can rise significantly. Reconstructive surgery post-mastectomy can push expenses up to INR 5,00,000. Private hospitals tend to charge more due to their advanced technology and experienced medical staff, whereas public hospitals offer comparatively affordable rates. Additional costs for diagnostics, pre-operative and post-operative care, as well as hospital stays, further contribute to the overall expense. Availability of financial assistance through health insurance, government schemes, and non-profit organizations can help alleviate these costs, making treatment more accessible to those in need.
ReplyDeletehttps://www.breastoncosurgery.com/services/breast-cancer-treatment-cost-in-delhi/
A premier colon cancer specialist in Ahmedabad is renowned for their exemplary expertise in diagnosing and treating colon cancer. With a wealth of experience and advanced training, they specialize in the latest techniques, including laparoscopic and robotic-assisted surgeries. Their individualized treatment plans are meticulously crafted to meet the unique needs of each patient, ensuring optimal outcomes. Affiliation with leading medical institutions grants them access to cutting-edge technologies and innovative research. Their continuous involvement in clinical trials ensures that patients benefit from the most current advancements in cancer care. Known for their compassionate and patient-centric approach, they have earned high praise from both peers and patients. This dedication to excellence has established them as a trusted authority in colon cancer treatment in Ahmedabad.
ReplyDeletehttps://drvirajlavingia.com/colorectal-cancer-specialist-in-ahmedabad
Dr. Aarti Patel is a highly skilled breast surgeon in Mumbai, recognized for her proficiency in oncoplastic surgery and minimally invasive procedures. Affiliated with premier hospitals offering advanced medical facilities, she ensures the highest quality of care. Dr. Patel's approach is meticulously patient-centric, crafting individualized treatment plans tailored to each patient's unique requirements. Her dedication to continuous education and participation in clinical research keeps her at the forefront of breast surgery advancements. Patients commend her for her empathetic communication, detailed explanations, and unwavering support throughout their treatment journey, which significantly contributes to their overall well-being and recovery.
ReplyDeletehttps://drnitanair.com/about/about-top-breast-cancer-surgeon-mumbai
Dr. Shona Nag is a renowned breast cancer specialist based in Pune, celebrated for her expertise and compassionate care. With extensive experience in oncology, she is dedicated to providing personalized treatment plans for her patients. Dr. Nag is known for her advanced knowledge in breast cancer therapies and her commitment to staying updated with the latest medical advancements. She has a strong focus on patient education and holistic care, ensuring her patients feel supported throughout their treatment journey. As a respected leader in her field, Dr. Nag is also involved in numerous research projects and clinical trials, contributing significantly to cancer care advancements.
ReplyDeletehttps://www.drshonanagbreastcancer.in/understanding-cancer/what-is-cancer-can-cancer-be-cured
Cheap Logo Designers in Delhi are dedicated to providing high-quality logo design services at competitive prices. Their team of creative graphic designers works closely with clients to understand their brand identity and deliver bespoke logos that resonate with the target audience. With an emphasis on originality and artistic flair, they ensure that each logo not only captures the essence of the brand but also stands out in a crowded marketplace. Quick turnaround times and a collaborative approach allow for extensive client feedback, making the design process smooth and efficient. They stay updated with the latest design trends to produce modern and appealing logos that reflect current aesthetics. The commitment to customer satisfaction drives them to refine designs until they meet and exceed client expectations. By choosing Cheap Logo Designers in Delhi, businesses can enhance their visual identity without straining their budget. Experience the transformative power of well-crafted logos that leave a lasting impression.
ReplyDeletehttps://olycoder.com/cheap-logo-designers-delhi
Advocate Rajkumar Solanki is widely recognized as the best divorce lawyer in Delhi, offering over 20 years of unparalleled experience in family law. Solanki excels in complex areas like asset division, child custody, and spousal support, providing strategic and personalized solutions. His client-focused approach ensures tailored guidance that aligns with individual needs and circumstances. Known for his superior negotiation skills, he seeks amicable resolutions, minimizing the need for court interventions. Solanki’s compassionate nature affords clients essential emotional support during arduous legal processes. His profound understanding of Delhi's legal system results in insightful and effective counsel. Confidentiality and trust are cornerstones of his practice, ensuring strong client relationships. With transparent communication and fair fee structures, Solanki sustains his esteemed reputation as a reliable and effective legal representative.
ReplyDeletehttps://bestdivorcelawyerindelhi.com/