Basic c++ program, what have i done wrong? [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am new to programming and found this exercise on a website. I tried completing it and this is how far i have got.
can someone please tell me if i am on the right direction, if not, what is wrong?
Also please explain any code you write.
"Write a program that prints the numbers from 1 to 100. But for multiples of three print Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
for (int i = 0; i < 100;i++ ){
while (i * 3 ){
cout << "Fizz"<<endl;
while (i * 5){
cout <<"Buzz"<<endl;
while ( 1 * 3 && 1*5){
cout <<"FizzBuzz"<<endl;
}
}

You're approaching things wrong. Why do you need the while (i*3)? Do you know what a while does? Is that supposed to check the remainder?
Hint - use conditionals (if) and the % operator to check the remainder.
No full code for you! Learn to debug! (this is the best thing you can do at this stage)

Replace
while (i * 3 ) {
with
if (i % 3 == 0) {
etc.

To test for divisibility test for remainder of 0 with %
whiles should be ifs
For loop will print 0 to 99
Try something like this:
for (int i=1; i <= 100; i++) {
if ((i%3 != 0) && (i%5 != 0)) {
cout << i;
}
else
{
if (i%3 == 0) {
cout << "Fizz";
}
if (i%5 == 0) {
cout << "Buzz";
}
}
cout << endl;
}

Related

Summation of Prime Numbers in C++ [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Hi guys I am working on a program to give the sum of all prime numbers under two million. Here's what I have... and I know this method works for finding prime numbers because I have used it before... however when I run this program I keep getting an infinite loop and no output.... any help would be greatly appreciated!
#include <iostream>
using namespace std;
int main (int argc, char * const argv[]) {
bool isPrime=true;
int i = 2;
int sum = 0;
do{
for ( int j = 2; j < i; j++)
{
if ( i % j == 0 )
{
isPrime=false;
break;
}
}
if (isPrime)
{
cout << "Prime: " << i << endl;
sum += i; // add prime number to sum
}
i++;
}while(i < 2000000);
cout << "the sum of all the primes below two million is: " << sum << endl;
getchar();
return 0;
}
The only logical error I can find is that you never re-set isPrime to true inside the loop, but that shouldn't cause an infinite loop, just wrong results.
I doubt it goes in an infinite loop though, I just think it takes a long time because it's sub-optimal. You don't need to check every number until i, sqrt(i) or even i/2 would do it.
Even better, you can generate a sieve of primes (google this) and then just add them up - this will be wildly more efficient.
I don't think you have an infinite loop. You forget to set isPrime to true, as Luchian Grigore noted, but your code will also take an awfully long time to run. Notice that you can stop doing trial division once j*j > i.
If you are also concerned about making things more efficient with minimum effort -- to get the primes you only need to check numbers of the form (6n + 1) and (6n + 5)
So including something like in your main loop :
int p6 = p % 6;
if (p6 == 1) {
result = isPrime(p);
p += 4;
} else if (p6 == 5) {
result = isPrime(p):
p += 2;
}
Will speed you up by a multiple. Don't forget the corner cases 2 and 3 though.

The UVa 3n + 1 in C++ with Dynamic Programming [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
So, there are ways to do this, and/or optimize this. Stupid that I am, I immediately wants to implement a recursive function, which later caused a segmentation fault, and then I tried to adopt dynamic programming, and it seemed to work, but somehow I got Wrong answer.
Problem Here
So here's my code, and I think it's pretty self-explanatory.
#include <iostream>
using namespace std;
int cycleLength(long long int);
int cycleLengthResult[1000000];
int main(int argc, char *argv[])
{
int i = 0, j = 0, cur = 0, max = 0;
while ( cin >> i >> j )
{
if ( i > j ) //swap to ensure i <= j
{
int s = i;
i = j;
j = s;
}
for ( int k = i ; k <= j ; ++ k )
{
cur = cycleLength(k);
if (cur > max) max = cur;
}
cout << i << " " << j << " " << max << endl;
max = 0;
}
}
int cycleLength(long long int arg)
{
if ( arg > 1000000 ) //if out of array bound, then don't memorize, just calculate
{
if (arg % 2 == 0)
{
return 1 + cycleLength(arg/2);
}
else
{
return 1 + cycleLength(arg*3+1);
}
}
if (!cycleLengthResult[arg-1]) //if result for arg doesn't exist then....
{
int valueForArg = 0;
if (arg == 1)
{
valueForArg = 1;
}
else if (arg % 2 == 0)
{
valueForArg = 1 + cycleLength(arg/2);
}
else
{
valueForArg = 1 + cycleLength(arg*3+1);
}
cycleLengthResult[arg-1] = valueForArg;
}
return cycleLengthResult[arg-1];
}
I passed all the sample inputs, and also (1, 1000000) for speed test. But it seemed that it's not the problem.
I want to fix my code, and not change the methodology used, of course, I can just not use recursive, and use a loop instead in main, which wouldn't overflow. But it's fun.
Read the statement carefully:
The integers i and j must appear in the output in the same order in which they appeared in the input
So save them after reading and print the saved values.

Is there anything wrong with this (c++)code? if so can anybody tell me where I went wrong? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm new to C++ and was practicing with an exercise. I use the CodeBlocks IDE.
#include <iostream>
using namespace std;
int main() {
double f;
double m;
int counter;
counter = 0;
for (f = 1.0, f <= 100.0, f++) { // error: expected primary-expression before ')'
m = f / 3.28;
cout << f << " feet is " << m << " meters!\n done";
counter++;
if (counter == 10) {
cout << "\n";
counter = 0;
}
}
cin.ignore();
cin.get();
return 0;
}
Every time I put this in my IDE I get the following error:
error: expected primary-expression before ')' token
Can anybody point me in the right direction?
You need to separate the clauses in your for statement with semicolons, not commas.
Also, it's cleaner to declare the loop variable inside the for:
for(double f=1.0; f<=100.0; f++) {
...
}
Your for loop statements are incorrectly separated by commas. Make them semi-colons:
for (f = 1.0; f <= 100.0; f++) {
}
for loops require semicolons between statements, so it should be:
for(f=1.0; f<=100.0; f++)
You're also missing a } after return 0;
Your for statement is improper:
for(f=1.0, f<=100.0, f++)
Should be:
for(f = 1.0; f <= 100.0; f += 1) // for(initial value; continuation condition; increment)
Essentially, you need to change those commas to semicolons.

Project Euler #19 [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Warning! Spoilers ahead!
You are given the following information, but you may prefer to do some
research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
At first, it seems like a simple problem. However, as I coded the solution, I ran into an odd problem - the answer should, in fact, be 171, but I get 173, whatever I do. I've looked over and over again my code, but nevertheless cannot find the bug.
#include <iostream>
using namespace std;
int main () {
int count = 0, days_in_month, days_passed = 1;
for (int i = 1900; i <= 2000; i++) {
for (int j = 1; j <= 12; j++) {
if (j == 4 || j == 6 || j == 9 || j == 11) {
days_in_month = 30;
} else if (j == 2) {
if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0)) {
days_in_month = 29;
} else {
days_in_month = 28;
}
} else {
days_in_month = 31;
}
if (days_passed % 7 == 0) {
count++;
}
days_passed += days_in_month;
}
}
cout << count << endl;
cin.ignore();
return 0;
}
Can anyone notice anything wrong with my code?
You are starting from 1900 i = 1900. The problem says "1 Jan 1901".

C++ prime number generator is not working [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
#include <iostream>
using namespace std;
int checkIfPrime(int num) {
for (int i = 1; i < num; i++) {
int result = num / i;
if (num == result * i) {
return 0;
}
}
}
int main() {
int i = 3;
while(1) {
int c = checkIfPrime(i);
if (c != 0) {
cout << c << "\n";
}
i = i + 2;
}
}
Sorry about posting the wrong code!
When I run this, nothing happens.. Can someone tell me what I am doing wrong?
After the question has completely changed its meaning:
Your CheckIfPrime is just wrong. You're checking divisibility in a very strange way. The general way to check whether a is divisible by b is if(a % b == 0)
That said, your error is that your loop starts with 1. Of course every number is divisible by 1, therefore by your logic, no number is prime. Start with for(int i = 2; .... (Depending on whether you want to consider 1 as prime or not, you might want to test specially for num == 1 initially.)
Also, the end condition is very inefficient. It is enough to check before the square root of num, that is i <= sqrt(num), but since sqrt is a rather slow and imprecise operation, MUCH better is to loop this way:
for(int i = 2; i * i < = num; ++i)
Another note - to generate all prime numbers from 1 to some MAX_VAL, your approach is very inefficient. Use the Sieve of Erastothenes.
Some stylistic note: your function should ideally return bool rather than int, and don't forget to return true or 1 after the loop has finished without returning.
Original Answer:
First of all, you need
fprintf(OUTPUT_FILE, "%d", Num); //d instead of s, no & before Num
instead of
fprintf(OUTPUT_FILE, "%s", &Num);
Second, you use the file I/O extremely inefficiently. Why do you open and close the file for every number? You should open it once, write all numbers, and then close it.
And thirdly, your algorithm doesn't seem to have anything to do with prime numbers... :)
By the way, since the first issue results in Undefined Behavior, you can't complain about any behavior of the program, since it's... well, undefined.
You aren't error checking any of your FileIO - wonder if something's going wrong there. A few ifs could help sort that out. Beyond that, all I see is an app that will fill your HDD real fast if it's working correctly.
The main reason why your prime generator isn't working, that i can see:
for (int i = 1; i < num; i++) {
int result = num / i;
if (num == result * i) {
return 0;
}
}
You start checking at 1. Since every number / 1 == itself, and every number * 1 == itself, the condition will always be true on the first run; that is, your prime test will always return false. Start at 2 instead.
Once you fix that, you should also make it so that the test returns true if it manages to get all the way through the loop. (Inserting a return 1; after the loop should be enough.)
(BTW, if you care the least bit about efficiency, if ((num & 1) == 0) return 0; for (int i = 3; i * i <= num; i += 2) would be better. But better still would be a sieve of some sort, as mentioned elsewhere.)
int checkIfPrime(int num) {
for (int i = 1; i < num; i++) {
int result = num / i;
if (num == result * i) {
return 0;
}
}
}
Missing return 1 at the end of the loop
The initial value of i must not be 1. Walk through the first iteration with a pencil and paper and see what happens.