The Code
int cycle_length(int i, int j) {
int cycleLength = 0;
for (int k = i; k <= j; k++) {
cout << algorithm(k) << endl;
if (algorithm(k) > cycle_length) {
cycleLength = algorithm(k);
}
}
return cycleLength;
}
ISO C++ forbids comparison between pointer and integer [-fpermissive]
I got this error in this line if ( algorithm(k) > cycle_length).
How is that, however, the same code works right in the main() ?? and what is this error mean ???
Added
algorithm is a function take an integer input and return an integer.
int algorithm(int number1) {
int counter = 1, number = number1;
do {
if (number % 2 == 0) {
number = number / 2;
counter++;
} else {
number = (3 * number) + 1;
counter++;
}
} while (number != 1);
return counter;
}
You are confusing the name of the function with your local variable of nearly the same name:
int cycle_length(int i, int j)
{
int cycleLength
Your function is called cycle_length, your variable is called cycleLength - yet you are using cycle_length further down.
The error message is slightly strange, because the compiler doesn't do "compare variable names with function names to see if there is one that is similar and then suggest that maybe you just typed it wrong" - it simply says "Hmm, you are comparing a function pointer [what you get from the name of a function] with an integer, that's not on!"
Related
I am trying to write divisor function, Which gives all divisor of given number. But in that I do not want any array rather I want to return every divisors one by one. Is it possible?
This is code :
auto allDivisor(int num){
for (int i=1; i<=num; i++){
if(num % i == 0){
return i;
}
}
But I got only first iterations result:
Enter integer number : 10 All divisior of 10 : 1
#include <iostream>
void allDivisor(int num, void (*callback)(int)) {
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
callback(i);
}
}
}
int main() {
int num = 10;
std::cout << "All divisors of " << num << ": ";
allDivisor(num, [](int divisor) {
std::cout << divisor << " ";
});
std::cout << std::endl;
return 0;
}
The callback function is passed to the allDivisor function as an argument, and it is called once for each divisor of the input number.
the usual way is to call your function multiple times and each time it will return different divisor until the end is marked by some special return value like 0 ... the iteration can be done either by passing i as function parameter or have it as global or static variable but that would make your function thread unsafe prohibiting to use it in parallel (even in serial overlapped with other division) ... It would look like this:
int allDivisor(int num)
{
static int i=0;
for (i++;i<=num;i++)
if ((num%i)==0) return i;
if (i>num){ i=0; return 0; }
}
and usage:
int d,X;
for (X=32;;)
{
d=allDivisor(X);
if (!d) break;
cout << d;
}
for (X=125;;)
{
d=allDivisor(X);
if (!d) break;
cout << d;
}
outputting this:
1
2
4
8
16
32
1
5
25
125
however be sure you always call the allDivisor until it returns 0 otherwise its next usage would be messedup (skipped first divisors until last i state) ... that could be repaired too for example like this (at cost of another static variable):
int allDivisor(int num)
{
static int i=0,n=0;
if (n!=num){ n=num; i=0; }
for (i++;i<=num;i++)
if ((num%i)==0) return i;
if (i>num){ i=0; n=0; return 0; }
}
I need to find the maximum remainder for n divided by any integer number from 1 to n, and the denominator which this remainder is found with.
In my implementation fun1 works as expected and returns the max remainder, fun2 is supposed to give 3 but its giving 2 .probably mistake is at break statement.
Sample input: 5
Expected output: 2 3.
My output: 2 2.
#include <iostream>
#include <algorithm>
using namespace std;
int fun2(int a);
int fun1(int n ,int num);
int main(){
int n = 0; int num = 0;;
cin >> n;
int p = fun1(n, num);
cout << p << "\n";
cout << fun2(p);
}
int fun1(int n, int num){
int b = 0;
for(int i = 1; i <= n; i++){
num = n % i;
b = max(num, b);
}
return b;
}
int fun2(int n,int p ){
int num = 0; int c = 0; int d = 0;
for(int i = 1; i <= n; i++){
num = n % i;
c = max(num, c);
if(c == p){
break;
}
d = i;
}
return d;
}
Since you already managed to successfully find the biggest remainder, you may get use of this function and return the number this remainder is found with:
std::pair<int, int> biggestRemDem(int value) {
int dm = 1;
int rm = 0;
for(int i = dm; i <= value; ++i){
const auto tmpRm = value % i;
if (tmpRm > rm) {
rm = tmpRm;
dm = i;
}
}
return { rm, dm };
}
The signature of the function needs to return std::pair however, but you no longer need the std::max, so the headers required to include are also changed:
#include <iostream>
#include <utility>
std::pair<int, int> biggestRemDem(int value);
int main(){
int n{};
std::cin >> n;
const auto result = biggestRemDem(n);
std::cout << result.first << " " << result.second << std::endl;
}
In fun2 you have:
if(c == p){
break;
}
d = i;
When you found the right index so that c == p the break will exit the loop and d == i; is not execute. Therefore d has the value from the previous loop, i.e. one less than you need.
Apart from that the code really smells:
fun1
should not have a second argument sum.
should remember the index where if found the largest remainder and you would be done
fun2
the maximum remainder is p, no need to max(num, c). Actually drop the c alltogether and just use num == p
n % 1 == 0 and n % n == 0. The loop will always break with i < n. Might as well not have a conditional: for(int i = 1; ; i++)
you need d because at the end of the loop i disappears. Why not pull i out of the loop? int i; for(i = 1; ; i++)
and now you can use a different conditional again
int fun2(int n,int p ){
int i;
for(i = 1; n % i != p; i++) { }
return i;
}
or
int fun2(int n,int p ){
int i = 1;
for(; n % i != p; i++) { }
return i;
}
or
int fun2(int n,int p ){
int i = 1;
while(n % i != p) ++i;
return i;
}
I need to find the maximum remainder for n divided by any integer number from 1 to n, and the denominator which this remainder is found with.
It seems that the asker decided to solve this in two steps. They wrote a function fun1 returning the maximum remainder and a function fun2, which fed with the previously calculated remainder, returns the corresponding dividend.
While not an efficient approach, it could work if implemented correctly, but that's not the case.
Other than some (very) bad naming choices, we can find:
In the original version of the posted code, fun2 has a function prototype with a single parameter and it is called passing the value returned by fun1, which is the maximum remainder. The problem is that this way the function has no way to know what was the original value of n and actually declares a local n, initialized to zero, so that the body of the loop for(int i = 1; i <= n; i++) is never executed.
The actual version of this question shows a definition of fun2 with two parameters, that can't compile unless both the prototype and the call site are changed accordingly.
Assuming that the original n and the remainder p were succesfully passed to fun2, there still would be another issue:
int fun2(int n, int p ) {
int c = 0, d = 0;
for(int i = 1; i <= n; i++) {
int num = n % i;
c = max(num, c);
if(c == p){ // So, if we reach the passed remainder...
break; // We break out of the loop, skipping...
}
d = i; // this line, meaning...
}
return d; // That the dividend previous to the correct one is returned!
}
They could just return i; when c == p.
The answer by The Dreams Wind presents a much better approach to this task. I'd like to suggest an O(1) solution, though. Consider these points:
The result of n % i can't be equal or greater than i. It's in the range [0, i).
n / 2 is the greatest number that can divide n other than n itself. It means that all the numbers i in (n/2, n) are such that n % i > 0.
For every number i in (n/2, n), we can actually say that n % i = n - i.
So, when n is greater than 2, the i corresponding to the maximum remainder is just 1 + n/2 and said remainder is n - n/2 - 1.
I need to resolve this problme "Write a recursive function called removeCharge that receives an N number and returns a number that contains only the digits of the original number." I made it but now i don't know how to display the number in the same function.What can I do?
int newNumber=0;
int eliminareCifreImpare(int n){
if(n==0)
return 0;
eliminareCifreImpare(n/10);
int c=n%10;
if(c%2==0)
newNumber=newNumber*10+c;
}
I guess you are using a global variable because you don't properly understand how to return values from functions. You need to get a good understanding of how functions return values and how to use returned values before you try to write recursive functions.
Here's a working version
#include <iostream>
int eliminareCifreImpare(int n) {
if (n == 0)
return 0;
int newNumber = eliminareCifreImpare(n / 10);
int c = n % 10;
if (c % 2 == 0)
newNumber = newNumber * 10 + c;
return newNumber;
}
int main()
{
std::cout << eliminareCifreImpare(12345) << std::endl;
}
I have to implement a counter that counts the number of additions in this recursive function, but i am not allowed to use global variables. Do you know how to do that? For example if the function has to call itself free times then my counter has to be put on three at the end of the function just before the return.
long lindh(unsigned int n) {
long lin = 0;
if (n == 1 || n == 2) {
lin = 1;
} else {
lin = 1 * lindh(n - 1) + 3 * lindh(n - 2);
}
return lin;
}
int main() {
long b = 0;
b = lindh(24);
cout << "lindhauer " << b << endl;
return 0;
}
You can change the function signature to be:
long lindh(unsigned int n, int &count)
Pass it the variable you want the count to end up in, in both the initial call and every recursive one. Increment count in the appropriate places.
You can define an overloaded lindh function that takes two arguments. The overloaded function takes two parameters, while the version called from main is the "base" function that just delegates to the overloaded function.
In addition, since you need to return both a lin value and count, you can return a std::pair<long, int> to denote the lin value and count. This eliminates the need for a global variable,
Here is an example:
#include <utility>
#include <iostream>
long lindh(unsigned int n, int &count)
{
long lin = 0;
if (n == 1 || n == 2) {
lin = 1;
} else {
++count;
lin = 1 * lindh(n - 1, count) + 3 * lindh(n - 2, count);
}
return lin;
}
std::pair<long,int> lindh(unsigned int n)
{
int count = 0;
return {lindh(n, count), count};
}
int main()
{
auto b = lindh(24);
std::cout << "lindhauer = " << b.first << "\ncount = " << b.second << std::endl;
}
Live Example
I'm trying to create a array of prime numbers done by calculation. As a project to learn coding. Ultimately to build my own math library so this is something I can add onto at a variety of levels as I learn to code c++.
The following is code that works great for printing prime numbers to the screen based on the search range, but my totalPrimes iterator is stuck at 1. So each time it places the last prime found in the PrimeNumbers[1] position.
Any advice would be awesome.
#include <iostream>
#include <array>
std::array<long, 10000000> PrimeNumbers={0};
void isPrime(long x);
int main() {
for (long i = 1; i < 10; i++) {
isPrime(i);
}
for(int h = 0; h < 10; h++) {
std::cout << "\nSecond Prime is : " << PrimeNumbers[h];
}
}
void isPrime(long x) {
int count(0), totalPrimes(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
if (count == 1) {
++totalPrimes;
std::cout << '\n' << x << " is a Prime number";
PrimeNumbers[totalPrimes] = x;
}
}
You're initializing totalPrimes to 0 every time the function runs. You would need to have totalPrimes as a global variable, or better yet (because global variables can become problematic), set it equal to the first available member of PrimeNumbers before you do anything else in that function.
Keep track of a position along with your PrimeNumbers array.
size_t nLastPos=0;
...
for(size_t x = 0; 1000 > x; ++x)
{
if(isPrime(x))
{
PrimeNumbers[nLastPos++] = x;
}
}
for(size_t i = 0; nLastPos > n; ++n)
{/* print out number PrimeNumbers[n] */ }
It looks like you're having some trouble with variable scoping. The reason for your problem (as I noted in the comment) is that totalPrimes is local, so you're creating a new integer variable and setting it to 0 every time the function is called.
However, you've made PrimeNumbers global and are having the isPrime function modify it, which doesn't look like good practice.
All of this can be fixed with a little restructuring to make the code nicer:
#include <iostream>
#include <array>
bool isPrime(long x);
int main() {
std::array<long, 10000000> PrimeNumbers={0};
int totalPrimes = 0;
for (long i = 1; i < 10; i++) {
if (isPrime(i)) {
std::cout << '\n' << i << " is a Prime number";
PrimeNumbers[totalPrimes++] = i;
}
}
for(int h = 0; h < 10; h++) {
std::cout << h << " Prime is : " << PrimeNumbers[h] << std::endl;
}
}
bool isPrime(long x) {
int count(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
return count == 1;
}
Your program can be re-structured little bit to make it easier to follow and debug.
Don't put things in isPrime other than the logic to decide whether a number is prime. Make sure it returns a bool. This will make the function a bit simpler and easier to debug.
Use the return value of isPrime in the calling function to perform other bookkeeping tasks.
The logic you have used to check whether a number is prime is incorrect. That needs to be fixed.
Here's an updated version of your posted code.
#include <iostream>
#include <array>
#include <cmath>
std::array<long, 10000000> PrimeNumbers={0};
bool isPrime(long x);
int main()
{
int totalPrimes = 0;
for (long i = 1; i < 10; i++)
{
if ( isPrime(i) )
{
std::cout << i << " is a Prime number" << std::endl;
PrimeNumbers[totalPrimes] = i;
++totalPrimes;
}
}
}
bool isPrime(long x) {
// 1, 2, and 3 are primes.
if ( x <= 3 )
{
return true;
}
// Even numbers are not primes.
if ( x % 2 == 0 )
{
return false;
}
// Check the rest.
long end = (long)std::sqrt(x);
for (long a = 3; a < end; a += 2) {
if ((x % a) == 0)
{
return false;
}
}
return true;
}
and its output:
1 is a Prime number
2 is a Prime number
3 is a Prime number
5 is a Prime number
7 is a Prime number
9 is a Prime number
Everybody is talking about how your totalPrimes variable is reset each time the function is called, and this is obviously true. You could return the value from the function and increment it from main, you could use global variables having the variable being defined outside of the function so that it's not reset each time inside the function or you could use
A static variable!
Take a look at this simple case. I have a function called up_two which increases the value of by two each time the function is called. The static variable int value has a memory of each time the function up_two() is called which increments value by two each time. If I were to use a just an integer it would always reset the value and have it be zero, which is what I initially defined it to be.
The advantage of using a static variable is that I can count how many times a function has been called, and I can keep my counter specific to a particular function.
#include <iostream>
using namespace std;
void up_two();
int main()
{
for(int i = 0; i < 10; i++)
{
up_two();
}
return 0;
}
void up_two()
{
static int value = 0;
cout << value << endl;
value += 2;
}
This program doesn't solve the particular problem that you want to solve, but if you figure out how the static variable is working, it should make your workflow easier.
The magic line here is this:
static int value = 0;
With it like this my program prints the following:
0
2
4
6
8
10
12
14
16
18
Without the static declaration, you just get 10 lines of zeroes
which is troublesome.
Hope that helps you optimize your program the way you want it to be.