Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
This is related to the "Project Euler Problem 14"
As I think, my logic and the code is good enough,but it may take few seconds to give the answer.
But when i run this code, the program stops when "starting_number" is around 103152(i can't remember the number exactly).
Can anybody please have a look at this code and, tell me where and what's wrong with this code.
Here's the code :
#include<stdio.h>
int starting_number;
int number_of_terms;
int j=0,k=0;
int term;
int main(){
for(starting_number=2;starting_number<1000000;starting_number++){
term = starting_number;
number_of_terms = 1;
while(1){
{
if(term%2==0){
term = term/2;
number_of_terms++;
} else if(term%2!=0){
term = 3*term + 1;
number_of_terms++;
}
}
if(term == 1) break;
}
if(j>=number_of_terms) //finding which chain is longer
j=j;
else if(j< number_of_terms) {
j= number_of_terms;
k=starting_number;
}
printf("\n%d",starting_number);
}
printf("\n%d(%d)\n",k,j);
return 0;
}
This one's mildly tricky, but your problem is here:
if(term == 1) break;
If the variable term becomes very large (as it can easily do) then it can overflow the int datatype.
When this happens term becomes negative. The C language modulus of a negative odd number is itself negative. Therefore, the end condition for your loop is never met.
Solve this problem by using a larger data type such as unsigned long long.
A less convoluted version of your code would appear as follows. Note that I have eliminated the global variables (those outside of your main function) because global variables are evil. I've replaced your infinite while-loop with a loop that uses an end condition. I've reduced duplication of code within the while-loop. I've eliminated the j=j case. Since printf is a slow function to run, I've commented out the prinft you had in the for loop, which improves the run-time significantly.
#include <stdio.h>
int main(){
int number_of_terms;
unsigned long long term;
int j=0,k=0;
for(int starting_number=2;starting_number<1000000;++starting_number){
term = starting_number;
number_of_terms = 1;
while(term!=1){
if(term%2==0)
term /= 2;
else
term = 3*term + 1;
number_of_terms++;
}
if(j<number_of_terms){ //finding which chain is longer
j = number_of_terms;
k = starting_number;
}
//printf("\n%d",starting_number);
}
printf("\n%d(%d)\n",k,j);
return 0;
}
And, indeed, using unsigned long long solves the problem.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
Now im having problems with the new code in terms of compiling. I have two great answers but chux's answer is addressed to rectify my code . So by his/her directions my new code is:
#include <math.h>
#include <conio.h>
int main()
{
int n,i,r;
printf("Enter A Number to know its prime or non prime");
scanf("%d",&n);
for(i=2;i<=n-1;i++)
{
if(n%i==0)
{r==1;
break;
}
}
if(r==1)
printf("%d is a non-prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
But on the output it show as 87 is a prime number. I don't know why. But can someone spot my mistake?
At few problems
Assignment vs. compare
if (r=1) assigns 1 to r, so if (r=1) is always true. Certainly a compare was needed, #Ry
// if (r=1)
if (r == 1)
No early break
OP's code: The value of r depends on the last iteration. Certainly once a factor is found, loop should exit.
for(i=2;i<=n-1;i++) {
if(n%i==0)
// r=1;
{ r = 1; break; }
else
r=0;
}
Incorrect functionality for n == 0,1
All values n < 2 incorrectly report as prime.
Inefficient
Code performs up to n loops. Only need to perform sqrt(n) loops. Tip: Do not use floating point math here for an integer problem.
// for(i=2;i<=n-1;i++)
for(i = 2; i <= n/i; i++)
Alternate
Only peek if you must code.
First off, " ... conio.h is a C header file used mostly by MS-DOS compilers to provide console input/output. It is not part of the C standard library or ISO C .." I was able to get the code to compile without that library file, so you may wish to consider removing it. As for as the code goes, well here is what I came up with:
#include <math.h>
#include <stdio.h>
int isPrime(int value) {
int i = 2;
for(; i < value; i++) {
if((value % i) == 0) {
return 0;
}
}
return value > 1;
}
int main(void){
int n=0,i=0, r=0;
char * s;
printf("\nPlase enter a number to learn if it is prime:");
scanf("%d",&n);
r = isPrime(n);
printf("\n%d is ", n);
s = (r==0)? " not a prime number" : "a prime number";
puts(s);
return 0;
}
After the user inputs a number, the code checks whether it is prime by calling the function isPrime(), a function that returns an int. isPrime is a simple function that attempts to factor a number.
See here for similar live code that I devised.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
#include <stdio.h>
int isPrime(int n){
int ndiv = 0;
int i;
for(i=1;i<=n;i=i+1){
if(n%i == 0){
ndiv = ndiv+1;
}
}
if(ndiv == 2){
return 1;
}
else{
return 0;
}
}
int nextPrime(int n){}
int main(){
int a = isPrime(7);
printf(a);
//printf(isPrime(4));
}
This code gives me a run time error, I think there's a problem here with the way I deal with data types while using a functions and the printf command, but I can't really figure it out. Help!
f in printf stands for "format". You need to supply a format string for printing: printf("%d\n", a)
Your isPrime is inefficient: you do not need to attempt dividing all the way up to the number itself. You could stop once you reach the square root of the number
Moreover, you could exit the loop early once you see that the number is not prime.
Once you fix these errors, your program would start running and producing the output that you expect.
Here is a small example of how to use printf. You can find more format specifiers here.
#include <stdio.h>
int main()
{
int a = 97;
int b = 98;
char hello[6] = "world";
printf("%d\n", a);
printf("%d\n", b);
printf("%s\n", hello);
return 0;
}
It is because your method of printing a variable is wrong. Here's the right one.
int main(){
int a = isPrime(7);
printf("%d",a);
}
I'm no C/C++ expert, but try
printf("%d", a);
%d is a format placeholder expecting an integer number, essentially.
That looks like an interesting isPrime function. Not very efficient at all, but different from what I have seen in the past. You can also loop over all the numbers between 1 and n, and just return false (or 0) if you find any that divise n. Or look up more efficient algorithms.
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
#include <stdio.h>
#include <stdlib.h>
#define size 20000000
int prim[size];
int i, zahl, zaehler, erg;
int sieve(int zahl, int prim[], int zaehler) {
if(zahl == 2000000)
return 1;
for(i=0; i<=zaehler; i++) {
erg = zahl%prim[i];
if(erg==0) {
zahl++;
return sieve(zahl, prim, zaehler);
}
}
zaehler++;
prim[zaehler]=zahl;
zahl++;
printf("%d\n", prim[zaehler]);
return sieve(zahl, prim, zaehler);
}
int main(){
zaehler = 0;
zahl = 2;
for(i=0;i<size;i++)
prim[i]=2;
sieve(zahl, prim, zaehler);
}
When trying to calculate prime numbers, when i run this code, it always crushes at the number 64901.
What might be the problem?
Ironically, this is literally a stack overflow due to recursion. You can make your stack large (which will only delay the issue), or change from a recursive solution to an iterative one.
(and for what it's worth, some debuggers won't be able to help you in this situation. And it's very difficult to beginners in C to understand what is going wrong until the first time they hit this problem. So congrats! You're leveling up in C)
A cheap way to verify it's indeed a stack overflow is to create extra memory on your stack in the recursive function and see if the number it crashes on changes from 64901. My guess is if you put like char dummy[2048] in there, it will crash much sooner.
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
i cant get the following code to run, ie it dosent give out any output
the objective is to find the sum of all primes below 2 million,
#include <stdio.h>
#include <math.h>
int is_prime(long long int i)
{
long long int n;
if(i==2)
return 1;
for(n=2;n<=sqrt(i);n++)
if(i%n==0)
return 0;
return 1;
}
int main()
{
long long int s=0,i=2;
for(i<2000000;i++;)
{
if(is_prime(i))
s=s+i;
}
printf("sum: %lli",s);
return 0;
}
You're using the for loop wrong. A for loop looks like this:
for(initialization; test expression; update)
But you wrote
for(i<2000000;i++;)
which should be
for(;i<2000000;i++)
ie, skip initialization, on each iteration test for i<2000000 and increment.
Your problem is that you are essentially factorising every integer up to two million for this. It's not that your code isn't working, it just is running very very slowly. If you attach a debugger to it you will most likely be at line
if(i%n==0)
most of the time.
Implement the Sieve of Eratostenes. Will be the most effective here.
Also your loop for(i<2000000;i++;) will run for 2^64 cycles.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I had to write a piece of code which would search a given value in an array.
I made this piece of code, which works:
#include <stdio.h>
int index_van(int searchedValue, int array[], int lengthArray)
{
int i ;
for (i = 0; i < lengthArray; i++)
{
if (array[i] == searchedValue)
{
return i;
}
}
return -1;
}
int main()
{
int array2 [] = {0, 1, 3, 4, 5, 2};
printf("%i", index_van(2, array2, 6));
}
With the correction (the teacher put up online) of this exercise the notes of my teacher were:
You have to quit the moment you have found your value ,so you can't search through the entire table if you have found your value already. A for-loop therefore isn't tolerated.
Even if the for-loop has an extra built-in condition, THIS ISN'T STYLISH!
// One small note ,she was talking in general . She hasn't seen my version of the exercise.
So my question to you guys is, is my code really 'not done' towards professionalism and 'style' ?
I think she's implying that you should use a while loop because you don't know how many iterations it will take to get you what you're looking for. It may be an issue of her wanting you to understand the difference of when to use for and while loops.
"...Even if the for-loop has an extra built-in condition..."
I think this right here explains her intentions. A for loop would need a built-in condition to exit once it's found what it's looking for. a while loop already is required to have the condition.
There is nothing wrong with your code. I have no idea if using a for loop is less stylish than using another, but stylish is a very subjective attribute.
That being said, don't go to your teacher and tell her this. Do what she says, a matter like this is not worth contradicting your teacher for. Most likely this is just a way to teach you how while loops work.
After accept answer:
I've posted this to point out sometimes there is so much discussion of "style", that when a classic algorithmic improvement is at hand, it is ignored.
Normally a search should work with a const array and proceed as OP suggest using some loop that stops on 2 conditions: if the value was found or the entire array was searched.
int index_van(int searchedValue, const int array[], int lengthArray)
But if OP can get by with a non-const array, as posted, then the loop is very simple and faster.
#include <stdlib.h>
int index_van(int searchedValue, int array[], int lengthArray) {
if (lengthArray <= 0) {
return -1;
}
int OldEnd = array[lengthArray - 1];
// Set last value to match
array[lengthArray - 1] = searchedValue;
int i = 0;
while (array[i] != searchedValue) i++;
// Restore last value
array[lengthArray - 1] = OldEnd;
// If last value matched, was it due to the original array value?
if (i == (lengthArray - 1)) {
if (OldEnd != searchedValue) {
return -1;
}
}
return i;
}
BTW: Consider using size_t for lengthArray.