Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to rewrite the Python algorithm in C++ and it doesn't work correctly.
I think the problem is that I can't rewrite the function correctly in C++. How do I write a constant to a function (in Python, this is the 'start' parameter) or an error in another one?
On Python 3:

def Algorithm(n, start = 2)

In this instance 'start' - constant.

I dunno how do I can write this on C++

What I have tried:

There is my C++ code:
C++
#include <iostream>
using namespace std;

int Algorithm(int, const int);
int main()
{
	const int start = 2;
	int num, ans;
	cin >> num;
	ans = Algorithm(num, start);
	cout << ans;
	return 0;
}

int Algorithm(int n, const int start = 2)
{
	if (n == 1) {
		return 1;
	}
	else {
		int ans = 0;
		int i;
		for (i = start; i <= n; i++)
		{
			if (n % 1 == 0) {
				ans += Algorithm(n / i, i + 1);
			}
		}
		return ans;
	}
}
And there is my Python code:
Python
def algorithm(n, start=2):
    if n == 1:
        return 1
    else:
        ans = 0
        for i in range(start, n+1):
            if n % i == 0:
                ans += algorithm(n // i, i + 1)
        return ans

n = int(input())
ans = algorithm(n)
print(ans)
Posted
Updated 14-Oct-20 23:47pm
v2
Comments
Richard MacCutchan 10-Oct-20 8:14am    
As I already suggested, your start value should be the number divided by 2. So you do not need a constant.

best is to write
C++
int Algorithm(int n, int start)
to avoid confusion.
 
Share this answer
 
The start parameter isn't a constant, it's a parameter with a default value. First, read about default argument values in Python[^] and in C++[^]. In C++ the default argument must be specified in the function declaration[^].

C++
#include <iostream>
using namespace std;

int Algorithm(int n, int start = 2);
int main()
{
    int num, ans;
    cin >> num;
    ans = Algorithm(num);
    cout << ans;
    return 0;
}

int Algorithm(int n, int start)
{
	if (n == 1) {
		return 1;
	}
	else {
		int ans = 0;
		int i;
		for (i = start; i <= n; i++)
		{
			if (n % 1 == 0) {
				ans += Algorithm(n / i, i + 1);
			}
		}
		return ans;
	}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900