I am very much a beginner in C++ and was just delving into for loops when I ran into a problem that I solved by winging it and not by understanding.
My script adds numbers from 1 to 10 and calculates the average. The thing is that I had to introduce a new variable "number", other than "sum" and "count", to not have the average be wrong.
#include <iostream>
int main ()
{
float count, sum, avg, number;
sum=avg=number=0.0;
for (count=1.0;count<=10.0;count+=1.0)
{
sum=sum+count;
avg=sum/count;
number=count;
}
printf("\n\nThe number of iterations is %1.f",number);
printf("\nThe sum of the numbers between 1 and 10 is = %.1f",sum);
avg=sum/number;
printf("\nThe average is %.1f",avg);
}
Produces the right result, but
#include <iostream>
int main ()
{
float count, sum, avg;
sum=avg=0.0;
for (count=1.0;count<=10.0;count+=1.0)
{
sum=sum+count;
avg=sum/count;
}
printf("\n\nThe number of iterations is %1.f",count);
printf("\nThe sum of the numbers between 1 and 10 is = %.1f",sum);
avg=sum/count;
printf("\nThe average is %.1f",avg);
}
Gives one more iteration than I expected and causes the average to be wrong. I assume that maybe calling "count" to print adds up but have no certainty and would really like to know why. Sorry if the question but I couldn't figure it out.
In this loop
for (count=1.0;count<=10.0;count+=1.0)
{
sum=sum+count;
avg=sum/count;
number=count;
}
number can not be greater than 10.0.
But in this loop
for (count=1.0;count<=10.0;count+=1.0)
{
sum=sum+count;
avg=sum/count;
}
count is greater than 10.0 after exiting the loop due to the condition count<=10.0.
So these statements
avg=sum/number;
and
avg=sum/count;
produce different results because number and count are unequal after the loops.
Related
I want to know how to calculate the TIME complexity for this program, the 10 in outer loop defines the number of primes to print. You can suppose it as N. for now this prints 10 prime numbers.
#include <iostream>
using namespace std;
int main()
{ int number=2;
bool flg=0;
cout<<2<<"\t";
number=3;
for(int count=1;count<10;number+=2){
for(int j = 3;j<(number/2);j+=2){
if(number%j==0){
flg=1;
break;
}
}
if(flg==0)
{cout<<number<<"\t";count++;}
else
flg=0;
}
return 0;
}
Assuming integer operations are counted as constant time and ignoring limited range of actual C++ integers:
Because of the prime number theorem, the outer loop will be iterated Theta(N ln(N)) times.
Asymptotically almost all of these iterations are for non-primes because the density of non-primes in the (odd) natural numbers is converging to one.
The inner loop for a non-prime m takes Theta(m) time.
Therefore, in total, the time complexity of the algorithm is Theta(N^2 ln(N)).
This problem is from hackerrank and the link is : https://www.hackerrank.com/challenges/sherlock-and-squares .
The program below prints the count of numbers that are perfect squares within the given range. However, I get an error of time limit exceeded as the constraints for testcases are 1 < testcase < 100 and for 2 integers in the range are 1 < number 1 < 10^9, 1 < number2 < 10^9 .
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<math.h>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int testcase;
cin>>testcase; //input testcase
while(testcase--)
{
int number1,number2,count=0;
cin>>number1>>number2; //input the limits
for(int i=number1;i<=number2;i++) //check for each number within the limits if it is a proper square
{
if(sqrt(i)==floor(sqrt(i)))
count++;
}
cout<<count<<endl; //print the total count of numbers that are perfect square within the limits
}
return 0;
}
Can someone please tell me how to optimize the problem further. As I am not able to figure out how time complexity can be further reduced.
I'm not going to code it for you. However :
Instead of testing every number, find the first perfect square in the range. Then, increment by one the square root of the perfect square. That gives you the next perfect square. Repeat until you reach the upper limit.
Expected improvement would be around the order of your numbers. If number1 is 1000, you'll be skipping around a thousand number at each step. That should pass easily.
As the number of squares is exactly the difference
between the square root of the next greater square number of number1 and square root of biggest square number below number2, you can use something like
cout << (int) ( floor(sqrt(number2)) - ceil(sqrt(number1)) + 1)
Check if number2 >= number1 and swap them otherwise.
is it copy paste code?
You get from input stream n1 and n2, but after that you using number1 and number2 which are not initialized.
I have a program that displays one random number in file .
#include <iostream>
#include <fstream>
#include <random>
using namespace std;
int main() {
std::ofstream file("file.txt",std::ios_base::app);
int var = rand() % 100 + 1;
file<<var ;
return 0;
}
Results after 4 trial :
1,2 2,20 3,40 1,88
I am looking to not display the numbers . but only there updated average after each try.
Is there any way to calculate the average incrementally ?
Inside the file should exist only the average value :
For example first trial :
1.2
second trial displays the average in the file (1.2+2.2)/2
1.7
Even though it's kind of strange, what you are trying to do, and I'm sure there is a better way of doing it, here's how you can do it:
float onTheFlyAverage()
{
static int nCount=0;
float avg, newAvg;
int newNumber = getRandomNum();
nCount++; //increment the total number count
avg = readLastAvgFromFile(); //this will read the last average in your file
newAvg = avg*(nCount-1)/nCount+ (float)(newNumber)/nCount;
return newAvg;
}
If for some reason you want to keep an average in a file which you provide as input to your program and expect it to keep on averaging numbers for you (a sort of stop and continue feature), you will have to save/load the total number count in the file as well as the average.
But if you do it in one go this should work. IMHO this is far from the best way of doing it - but there you have it :)
NOTE: there is a divide by 0 corner-case I did not take care of; I leave that up to you.
You can use some simple math to calculate the mean values incrementally. However you have to count how many values contribute to the mean.
Let's say you have n numbers with a mean value of m. Your next number x contributes to the mean in the following way:
m = (mn + x)/(n+1)
It's bad for performance to divide and then multiply the average back. I suggest you store the sum and number.
(pseudocode)
// these variables are stored between function calls
int sum
int n
function float getNextRandomAverage() {
int rnd = getOneRandom()
n++;
sum += rnd;
float avg = sum/n
return avg
}
function writeNextRandomAverage() {
writeToFile(getNextRandomAverage())
}
Also it seems strange to me that your method closes the file. How does it know that it should close it? What if the file should be used later? (Say, consecutive uses of this method).
http://www.spoj.com/problems/NDIV/
This is the problem statement. Since i'm new to programming, this particular problem ripped me off, I found this particular code on the internet which when I tried submitting got AC. I want to know how this code worked, as I have submitted it from online source which itself is bad idea for beginners.
#include <bits/stdc++.h>
using namespace std;
int check[32000];
int prime[10000];
void shieve()
{
for(int i=3;i<=180;i+=2)
{
if(!check[i])
{
for(int j=i*i;j<=32000;j+=i)
check[j]=1;
}
}
prime[0] = 2;
int j=1;
for(int i=3;i<=32000;i+=2)
{
if(!check[i]){
prime[j++]=i;
}
}
}
int main()
{
shieve();
int a,b,n,temp,total=1,res=0;
scanf("%d%d%d",&a,&b,&n);
int count=0,i,j,k;
for(i=a;i<=b;i++)
{
temp=i;
total=1;
k=0;
for(j=prime[k];j*j<=temp;j=prime[++k])
{
count=0;
while(temp%j==0)
{
count++;
temp/=j;
}
total *=count+1;
}
if(temp!=1)
total*=2;
if(total==n)
res++;
}
printf("%d\n",res);
return 0;
}
It looks like the code works on the sieve of eratosthenes, but a few things i'm unable to understand.
Why the limit of array "check" is 32000?
Again why the limit for array prime is 10000?
Inside main, whatever is happening inside the for loop of j.
Too many confusions regarding this approach, can someone explain the whole algorithm how it's working.
The hard limit on the arrays is set probably because the problem demands so? If not then just bad code.
Inside the inner loop, you are calculating the largest power of a prime that divides the number. Why? See point 3.
The number of factors of a number n can be calculated as follows:
Let n = (p1)^(n1) * (p2)^(n2) ... where p1, p2 are primes and n1, n2 ... are their exponents. Then the number of factors of n = (n1 + 1)*(n2 + 1)...
Hence the line total *= count + 1 which is basically total = total * (count + 1) (where count is the largest exponent of the prime number that divides the original number) calculates the number of prime factors of the number.
And yes, the code implements sieve of Eratosthenes for storing primes in a table.
(Edit Just saw the problem - you need at least 10^4 boolean values to store the primes (you don't actually need to store the values, just a flag indicating whether the values are prime or not). The condition given is 0 <= b - a <= 10^4 , So start your loop from a to b and check for the bool values stored in the array to know if they are prime or not.)
I want to use a while loop to divide n numbers and print the quotient. For example if the user entered n=3, the program will ask for 3 numbers. Say the user entered 2, 2, and 3. The program then performs the following operation: 2/2/3 and then prints the answer ( i.e. 0.3333). I have a program that uses a while loop for addition, division, and multiplication perfectly, but in division, it divides 1 by all the numbers entered(1/2/2/3). How do I fix it? Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main(void)
{
int n, k=0;
float total=1, number;
printf("\nEnter the number of elements you want to divide:");
scanf("%d",&n);
printf("Please enter %d numbers one by one: \n",n);
while(k<n)
{
scanf("%f",&number);
total=number/number;
k=k+1;
}
printf("Quotient of %d numbers = %f \n",n,total);
_getch();
}
Change
total=number/number;
to
if (k==0)
total = number;
else
total=total/number;
Start with k=1 then right before the while loop put
scanf('%f', &total);
You might want to wrap that line in if (n!=0). This way there's no if statement in the loop for very marginal, minuscule performance gains!
Then just change
total=number/number;
to
total=total/number;
and you should be set to go.