Display powers in C++ loop [closed] - c++

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

Related

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).

C++ program doesn't fully execute iteration [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 4 years ago.
Improve this question
The program I've written is supposed to take in two user inputs (one being the number we're meant to check whether it's k-hyperperfect or not, the other being a maximum k-value.) if the input integer is k-hyperperfect in the range of 1 to the inputted maximum k-value, then the output should be that k-value. For example, if the input integer is 21 and the maximum k-value is 100 then the output should be 2.
My program gives the correct output for (the first number is the input integer, the second number is the k-max value, the third number is output value) ...
21 (input integer) 100 (k-max) --> 180
301 100 --> 6
12211188308281 100 --> 0
-301 100 --> 0
21 -5 --> 0
However, it doesn't correctly execute for 12211188308281 and 200 (it gives me 0 when it should give me 180). I've run my code through a step by step visualizer and it seems to just abruptly stop execution when i = 496 in the for loop within the else statement. But I don't understand why since it executes correctly for 5 other test runs.
#include <iostream>
using std::cout; using std::cin; using std::endl; using std::fixed;
int main () {
int number;
int kmax;
int sum = 0 ;
int hyper = 0;
std::cin >> number;
std::cin >> kmax;
if (number <= 6 or kmax < 1) {
std::cout << "0" << "\n";
}
else {
for (int i=1;i<=number;i++) {
if (number%i==0 and i != 1 and i != number){
sum+= i;
}
}
}
for (int k=1; k <= kmax; k++) {
hyper = ((sum)*k) + 1;
if (hyper == number) {
std::cout << k << endl;
break;
}
}
}
You need to check that numbers read through std::istreams (like std::cin) are read successfully. As the value that you enter for number is too large to store in an integer your read will fail. For example you could change your code to:
int main()
{
int number;
std::cin >> number;
if ( !std::cin )
{
std::cout << "invalid value: " << number << "\n";
return 1;
}
else
{
std::cout << "valid value: " << number << "\n";
}
// calculate answer
return 0;
}
You would then see your program printing "invalid value: 2147483647" if you have a c++11 compliant compiler or an undefined number if you have an older compiler.
Now that you have implemented reading values correctly the fix to your issue is to use a larger integer type like int64_t which is able to hold your number.
As already noted, the int type in your machine isn't big enough to store the value 12,211,188,308,281.
The C++ standard only mandates it to be capable of storing a value up to 32,767 and even in the (now common) case of a 32-bit int or long int), the limit would be 2,147,483,647. So you need a long long int or an int64_t (if it's present in your implementation).
A simple check like
if (std::cin >> number >> kmax ) { // perform calculations...
Would have shown the error sooner.
That beeing said, there are also some simple changes that could be done to the posted code in order to make it more efficient. The first loop can be optimized considering the "symmetry" of the divisors of a given number: meaning, if n is divisible by a, so that b = n/a is a whole number, b too is a divisor of n. This will limit the number of iterations to the square root of n, instead of n.
long long int number,
kmax,
sum = 0;
// ...
long long int temp = number,
i = 2;
for (; i * i < number; i++) {
if (number % i == 0) {
temp = number / i;
sum += i + temp;
}
}
if (i * i == number) {
sum += i;
}
There probably are better algorithms, but I'm unfamiliar with those.
The second loop, in my opinion, is unnecessary. The value k can be calculated directly:
if ( (number - 1) % sum == 0) {
std::cout << (number - 1) / sum << '\n';
}
You are assigning a too long value 12211188308281 to integer "number", which can't contain it fully and it is getting truncated to 596285753. You can add a print statement to print it.
std::cout<<number;
which will print 596285753.
As suggested you should use long long int. Again its dependent on the software platform running on your system.

Getting Only Even Numbers in C++ [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 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.

How to calculate how many times a number goes into another number [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 6 years ago.
Improve this question
This is the program with the initial 'number' stated in the question taken as 'n' and the 'other number' taken as 10.
void divideme()
static int count=0; //initalised a variable which I'll be returning the value of.
int n;
cin>>n;//taken input of variable which I want to divide by another number (say 10 in this case)
int &rem=n;//created a reference variable which stores the value of n.
while (rem>=10) {
rem=rem%10; //this is to be corrected as rem = rem - 10;
count++;
}
return count;
Your code is overkill. Just do the division one time. The result is the number of times 10 goes into the number. No loop is needed at all. The % operator gives you the modulus (remainder) of a division, which is not what you need in this situation.
int divideme()
{
int n;
cin>>n; //get input which I want to divide by another number (say 10 in this case)
return (n / 10);//return how many times it divides by 10
}
For example:
9 / 10 = 0
9 % 10 = 9
10 goes into 9 0 times, with a remainder of 9.
12345 / 10 = 1234
12345 % 10 = 5
10 goes into 12345 1234 times, with a remainder of 5.
The % operator give you the modulus, which is the remainder after division.
If you just want to count the number of times that 10 goes into a number rem, then replace
rem=rem%10;
with
rem = rem - 10;
in your loop.
(Also, you don't need if (rem>=10) in your code. The while loop takes care of this.)
#include <cmath>
#include <iostream>
int times_divided_by_10(int x)
{
return int(std::log10(double(x)));
}
int main()
{
std::cout << times_divided_by_10(101) << std::endl;
}
expected output:
2
another way:
#include <iostream>
int times_divided_by_10(int x)
{
int count = 0;
while (x >= 10) {
++count;
x /= 10;
}
return count;
}
int main()
{
std::cout << times_divided_by_10(101) << std::endl;
}

Two Q. That were on my Procedural Programming exam no one answered correctly [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
By the way, this was a written exam. These questions gave 4 points each out of a possible 100.
Question 1:
Write a small program that by using a single while-loop and an if-statement will print out the following on the screen: [warning: multiple numbers out in a string, or hard-coding the values into variables will give zero points]
1 4 9 16 25
1 4 9 16
1 4 9
1 4
1
Question 2:
Below is the equation for the Harmonic Mean. Write a small program that can take values of an array and calculate the harmonic mean of these.
x = n * ( n Sigma i=1 (1/xi) )
Do you have any answers?
Question 1:
#include <iostream>
int main()
{
int i = 1;
int j = 5;
while(j > 0)
{
std::cout << i*i << " ";
if(i == j)
{
i = 1;
--j;
std::cout << "\n";
}else
{
++i;
}
}
}
Output:
1 4 9 16 25
1 4 9 16
1 4 9
1 4
1
Good enough?
Live example
Since recursion was not forbidden one could try this:
#include <iostream>
void printLn(int i) {
int j = 0;
while(++j <= i)
std::cout << j*j<<" ";
std::cout << "\n";
if(i > 1)
printLn(i - 1);
}
int main() {
printLn(5);
}
See it working at: http://ideone.com/mrKUx0
It uses recursion to print the individual lines and the while loop to print each number in the lines. The if is used to abort the recursion when finished.
The other code is very straight forward:
#include <iostream>
const int ARRAY_SIZE = 5;
int main() {
float array[ARRAY_SIZE] = {1, 2, 3, 4, 5};
float sum = 0;
for(int i = 0; i < ARRAY_SIZE; ++i)
sum += 1 / array[i];
std::cout << "Harmonic Mean: " << ARRAY_SIZE / sum;
}
Again see: http://ideone.com/GQJqQn
Note that the harmonic mean is defined as n/Sum(...) not n * Sum(...)