Getting Only Even Numbers in C++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm currently attempting to go through Project Euler to increase my understanding of C++, but I'm stumped on problem 2 on the part of how to get only even numbers in a Fibonacci sequence. I'm 99% sure that you have to use the % operator just from things I've looked at online, but all I understand of it is that it takes the remainder of something (ex 11/3 = 9 w/ remainder of 2), and so I have no idea on how to incorporate it into the code.
The problem: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
using namespace std;
int main()
{
int first = 1;
int second = 2;
int next;
cout << first << endl;
cout << second << endl;
if (next < 4000000)
{
for (int i = 0; i < 500000; i++)
{
next = first + second;
first = second;
second = next;
}
}
cout << next << endl;
return 0;
}

You need to check the evenness of number using modulo operator.
for (int i = 0; i < 500000; i++) {
next = first + second;
if(next%2 == 0) {
cout << next << "\n";
}
first = second;
second = next;
}
For more details about modulo operator please read the given link.

Related

minimum number of moves required to convert a given into a lucky number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
You are given a number, at a time either you can increase a number by 1 or decrease by 1 it is considered as one move find the minimum number of moves required to convert a given into a lucky number. A number is called lucky if all the digits in it are even.
I have writtern the code but I am not sure if it is correct. Can anybody please confirm me?
#include<bits/stdc++.h>
using namespace std;
int count(int n)
{
int count = 0;
while (n != 0)
{
n = n / 10;
++count;
}
return count;
}
int firstDigit(int n)
{
// Remove last digit from number
// till only one digit is left
while (n >= 10)
n /= 10;
// return the first digit
return n;
}
int main()
{
int n;
cin >> n;
int i,j,ans=0;
int x = count(n);
while(x--)
{
if(firstDigit(n)%2 != 0)
{
if(firstDigit(n) == 9)
{
ans = ans + pow(10,x);
n = n-pow(10,x);
}
else
{
ans = ans + pow(10,x);
n = n + pow(10,x);
}
}
else
n = n - pow(10,x);
}
cout << ans << endl;
}
Edit:
I found it is giving wrong answer at 100. Can you please help me in finding out the mistake
Not all code can easily be tested, thats why you should strive to write testable code right from the start (instead of first writing it all and then try to confirm correctness). In your case testability could benefit a lot from moving most logic from main into a dedicated function:
int minimal_steps(int input) {
....
}
Once you have that, you can either call it in main with user supplied input just as you do it now, but you can also write tests more easily:
void test() {
assert( minimal_steps(2222) == 0);
assert( minimal_steps(2221) == 1);
...etc...
}
Once you got into the habit of testing your code (you should also write tests for count and firstDigit) you may consider to use a testing framework to automate tests.
PS: It isnt wrong, but it is such a waste of CPU cycles that it is worth mentioning (actually it was already mentioned in a comment). You do not need to compute pow(10,x) in a loop where x is the loop counter. Consider that you are computing 10^2 almost as many times as the loop has iterations. Also 10^3 is the same in every iteration. Instead you should only update with *10 (in case x is incremented) or /10 when x decrements between iterations. Moreover, pow is for floating-points, not for integers.

how do I check how many int digits are inside and reset it to zero? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to do the same but the variable gram can be any other number but no more or less than 3 characters.
I also need to immediately reset n if the if condition is met
int gram = 123, n = 0; // gram = 241, gram = 333, gram 512. etc
for (int i = 0; i < 10; i++) {
n = 1000 * n + gram;
if (n == 123123123) // <--- here I don't know how to write a check
{
std::cout << " true: " << n << std::endl;
n = 0;
}
std::cout << n << std::endl;
}
I was able to do this
int tik++;
if (tik % 3 == 2) // But I don't like that the number tik keeps increasing.
{
std::cout << " true: " << n << std::endl;
n = 0; // <-- I want to get rid of that too
tik = 0; // <-- I want to get rid of that too
}
there is another question how to reverse the order of adding numbers to the variable n
I want to add not back but ahead.
n = 1000 * n + gram;
If you know gram is precisely three digits, given your multiply by 1000 and add approach, you can just have an inner loop that runs precisely three times, or a test for i % 3 == 2 to reuse information from the outer loop's loop variable.
If the value isn't fixed, and you need to stop at or above 9 digits, just use the log10 family of functions and trigger on the result being >= 8.0 (log10 of 100,000,000 is 8.0; log10 is a convenient way to count digits in base 10).

Display powers in C++ loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have to solve following exercise
Write a program to display 1,5,25,125 upto n terms.
I am in 11th grade and I have tried of many ways of writing this program.
Value of control variable is one, and it's less than n.
But by how much should it differ so that it obeys the above question?
Please answer if you could in simple language.
Also should I use a special variable for power?
Thanks in advance, Abhijith
Print out the old value times five, starting with 1
Basic mockup:
auto PrintExercise(std::size_t terms) -> void {
std::size_t lastResult = 1;
for (std::size_t i = 0; i < terms; ++i) {
std::cout << std::to_string(lastResult) << std::endl;
lastResult *= 5;
}
}
Edit: Turns out I overthought this. It would be easier to just print the power of the control variable.
auto PrintExercise(std::size_t terms) -> void {
for (std::size_t i = 0; i < terms; ++i) {
std::cout << std::to_string(pow(5,n)) << std::endl;
}
}
Since the correct answers have already been provided, here's the same approach using recursion instead of iteration (loops) with (hopefully) enough comments to explain the process. Just for completeness. Give it a try, it's fun!
#include <iostream>
//value = the value that will be printed
//end = after how many iterations you want to stop
void PowerOfFive( const int value, const int end )
{
//Print the current value to the console. This is more or
//less everything the function does...
std::cout << value << ", ";
//... but a function can also call itself, with slightly different
//values in this case. We decrement "end" by 1 and let the whole
//process stop after "end" reaches 0. As long as we're doing that,
//we're multiplying "value" by five each time.
if ( end != 0 )
{
PowerOfFive( value * 5, end - 1 );
}
}
int main()
{
//Example for the above
//Start:
// 1st PowerOfFive(1, 3)
// --> prints 1
// --> calls 2nd PowerOfFive(1 * 5, 3 - 1)
// --> prints 5
// --> calls 3rd PowerOfFive(5 * 5, 2 - 1)
// --> prints 25
// --> calls 4th PowerOfFive(25 * 5, 1 - 1)
// --> prints 125
// --> function 4 ends because "end" has reached 0
// --> function 3 ends
// --> function 2 ends
// --> function 1 ends
PowerOfFive( 1, 3 );
getchar( );
return 0;
}
It seems you want to print powers of 5 upto n, not sure what you mean by control variable. So this should work
for (int i=0;i<=n;++i) cout << pow(5,i) << ", " ;
Iteration value is by 5, it can be done with pow() function & also by using simple for loop like this.
power=0;
cout<<power;
for(i=0;i<n;i++)
{
power=power*5; // OR power*=5
}
cout<<power;
Im adding code see if it helps
#include<iostream>
#include <cmath>
using namespace std;
int main()
{
int exp;
float base;
cout << "Enter base and exponent respectively: ";
cin >> base >> exp;
for(int i=0;i<exp;i++)
{
cout << "Result = " << pow(base, i);
}
return 0;
}
You have to pass the base and exponent value and for your question it should be base=5 and exp=3 and your output will be till 1 , 5 ,25

Why does this code not display the correct answer to the calculation and why does it loop infinitely?? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to use the calculations to separate the numbers and then square them and then add
them together. So 79 would become 7 and 9. Then I want it to square 7 and 9 and add the results.
And do it all over again until I have 50 results or the result becomes 1. Also it loops
infinitely. Any ideas??
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
using namespace std;
int main ()
{
int number = 79;
int newNumber1;
int newNumber2;
int digit1;
int digit2;
int count;
int counter = 1;
while(number != 1 && counter != 50)
{
for(count = 1; count <= 10; count++)
{
cout << setw(8) << number;
counter++;
digit1 = number / 10;
digit2 = number % 10;
newNumber1 = pow(digit1 , 2);
newNumber2 = pow(digit2 , 2);
number = newNumber1 + newNumber2;
}
}
cout << endl << endl;
return 0;
}
The inner for loop will run 10 times per each of the outer loop iterations. This means that at the first outer loop iteration it counter will be 1, the second 11, the third 21, the fourth 31, the fifth 41 and the sixth 51; therefore the condition counter != 50 should really be counter < 50.
The logic behind number seems also flawed somehow. In the first iteration newNumber1 = 49 and newNumber2 = 81 so you have number = 49 + 81 = 130. Now the next iteration you have newNumber1 = 13 ^ 2 and newNumber2 = 0. So this number seems to always increase.
number = 1 will happen only when you have newNumber1 = 1 and newNumber2 = 0 or viceversa. This happens only when you have either digit1 or digit2 that are = 1. This only happens when number = 10, but number = 10 seems to never happen. So the condition number != 1 doesn't mean much.

C++ Creating a phone number generator [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm working on a C++ project and have run into an issue that is leaving me puzzled. I am to create a phone number generator that has the user enter the first 4 numbers, and then generate all possible phone numbers that follow these two rules:
The last 6 digits must equal 33.
The 4th and 5th digit cannot both be even or both be odd.
This is what I've come up with so far:
#include <iostream>
using namespace std;
int main()
{//begin main
srand(time(0));
const int MAX_DIGITS = 10;
int num[MAX_DIGITS] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
cout<<"enter the first digit: ";
cin>>num[0];
cout<<"Enter the second digit: ";
cin>>num[1];
cout<<"Enter the third digit: ";
cin>>num[2];
cout<<"Enter the fourth digit: ";
cin>>num[3];
for (int e=0;e<MAX_DIGITS;e++)
{
for(int f=0;f<MAX_DIGITS;f++)
{
for(int g=0;g<MAX_DIGITS;g++)
{
for(int h=0;h<MAX_DIGITS;h++)
{
for(int i=0; i<MAX_DIGITS;i++)
{
for(int j=0;j<MAX_DIGITS;j++)
{
if ((num[e]+num[f]+num[g]+num[h]+num[i]+num[j]) == 33 && (num[3]%2 != 0 && num[4]%2 != 0) )
{
cout<<num[0]<<num[1]<<num[2]<<num[3]<<num[e]<<num[f]<<num[g]<<num[h]<<num[i]<<num[j]<<endl;
}
}
}
}
}
}
}
It all makes sense to me so far, but the program is displaying some numbers multiple times, and I'm not entirely certain how to make sense of the even/odd rule.
I'm still a rookie to programming and I'm sure that there may be a more efficient way to do this, but I'm trying my best and this has left me puzzled. Any help would be appreciated.
Thanks in advance!
EDIT: My question is this, how do I get the generator to display the numbers with the even/odd rule applied? My best idea was to use the modulus operator (%) to see if the remainder of the numbers divided by two was zero, and if so, the numbers were even. This is where I stumble a bit though, because I'm not perfectly certain how to implement this. Sorry for not being more specific the first time.
1) You're not ever changing the values in the num array, so testing to see if it contains a valid number doesn't work because the initial values you set don't fit the rules.
2) The validation is checking to see if both numbers are odd, not one or the other.
Here's a version that seems to work. The changes I made are to actually change the num array and then use a helper function to validate the numbers in the array so you don't have a mess inside your loops. I removed the srand call since you aren't using random numbers and the input of the first 4 digits to make testing easier for me. You can add that back if you like.
#include <iostream>
const int MAX_DIGITS = 10;
bool IsValid(int num[MAX_DIGITS])
{
int sum = 0;
for(int z = 4; z < MAX_DIGITS; ++z)
{
sum += num[z];
}
if(sum != 33)
{
return false;
}
int numodd = 0;
for(int z = 3; z < 5; ++z)
{
numodd += (num[z] % 2);
}
if(numodd != 1)
{
return false;
}
return true;
}
int main()
{
int num[MAX_DIGITS];
num[0] = 5;
num[1] = 5;
num[2] = 5;
num[3] = 1;
for (int e=0;e<MAX_DIGITS;e++)
{
num[4] = e;
for(int f=0;f<MAX_DIGITS;f++)
{
num[5] = f;
for(int g=0;g<MAX_DIGITS;g++)
{
num[6] = g;
for(int h=0;h<MAX_DIGITS;h++)
{
num[7] = h;
for(int i=0; i<MAX_DIGITS;i++)
{
num[8] = i;
for(int j=0;j<MAX_DIGITS;j++)
{
num[9] = j;
if(IsValid(num))
{
for(int z = 0; z < MAX_DIGITS; ++z)
{
if(z == 3 || z == 6)
{
std::cout << '-';
}
std::cout << num[z];
}
std::cout << std::endl;
}
}
}
}
}
}
}
}