I'm struggling with this (optional) problem my professor recommended I try. Basically, my task is to write a program which displays all prime integers from 2-10,000 using my own user-defined function to determine prime-ness. It sounded simple enough but I'm having major difficulties debugging my program. For some reason, my code only displays 2 and 3 before ending.
#include<stdio.h>
//function declaration
int prime(int);
//main body
int main(void)
{
int x=2, y;
for (x=2;x<=30;x++)
{
y=prime(x);
if (y!=0)
printf("%d\n", x);
}
getchar();
return(0);
}
//function definition
int prime(int x)
{
int y;
for (y=2; y<=(int)sqrt(x); ++y)
{
if (x%y==0)
return 0;
}
if (y==(int)sqrt(x))
return 1;
}
Instead of returning 1 if x is prime, my prime checking function seems to return a random large number (2686xxx) but that shouldn't be an issue because all primes return 0. If I run something like:
if (y==0)
printf("%d\n", x);
I see a list of all non prime numbers. If I run something like:
printf("%d %d\n", x, y);
I see a list of all integers from 2-10,000 and the result of my prime checking function (0 for non-primes, 2686xxx for primes).
Why doesn't the opposite (y!=0) display a list of prime numbers? What is causing my code to stop after just displaying 2 and 3? Why is my prime function returning a weird integer instead of 1? Finally, I'm still a beginner but how can I write better code in general? I don't think I'm breaking any of the standard accepted practices but how can I make my code more clean or efficient?
Thanks in advance for the help!
Your loop continues if y==(int)sqrt(x). So when it finishes, they're not equal. What you wanted is:
if (y>=(int)sqrt(x))
return 1;
But this is not needed at all. Just return 1; is sufficient. You've already returned zero if the number isn't prime.
If you wanted only a single return statement:
int prime(int x)
{
bool isPrime = true;
int y;
for (y=2; y<=(int)sqrt(x); ++y)
{
if (x%y==0)
{
isPrime = false;
break;
}
}
return isPrime;
}
Don't use the sqrt() function. In mathematics if you have 'x = sqrt(y)'. If you square both sides you will get something like this 'x * x = y'. This expression in c is tremendously faster than the sqrt function. Thus instead of doing:
y <= (int)sqrt(x)
Have you for loop guard be something like this:
y * y <= x
Here is a running example of your problem:
Primes 2 -> 10000
At the end of your prime function just return 1. If it wasn't prime it would have returned 0 earlier. Right?
As it is you've made a function which sometimes returns nothing at all. Which means that it returns whatever random value happens to be in the register.
You can use sieve of eratosthenes or sieve of atkin to mark all the prime numbers in an array and then display the prime numbers. It will be time efficient although it incurs some space complexity.
e.g if you want to display prime numbers from 1 to 10
Leave of 1. Its not a prime. Its neither prime nor composite.
So start from 2.
consider this array of size 10 = 2 3 4 5 6 7 8 9 10
Traverse from 2. If an element is not highlighted highlight all its multiples.
i.e for 2 highlight its multiples 4 6 8 10
==> 2 3 4 5 6 7 8 9 10
For 3 do the same
==> 2 3 4 5 6 7 8
9
10
Then do it for the rest of the no.s i.e. 5 and 10 (Here 7 dont have multiple)
Finally print the non highlighted elements. 2,3,5,7.
Repeat this procedure for any other ranges.
Since you are interested in writing computer programs for prime numbers, perhaps you would like to turn this paper into a computer program. It deals with prime numbers and is similar to the sieve you were trying to create in C.
https://graviticpropulsion.files.wordpress.com/2015/04/prime-number-theory.pdf
I'm not sure if it is faster or less memory intensive, but I'm curious myself how high of a prime number it can find before it becomes too intensive for a computer.
Related
I have written code to find the units and tens digit of a number,but am facing a problem when the number is greater than 99.The value of i has been set to less than 10 inside the for loop but when i execute the code with no=100,I find that i has a value of 10.
Why is this happening?
#include <stdio.h>
int unit(int x){
return x%10;
}
int ten(int x){
int temp=x-unit(x);
if(temp==0){
return 0;
}
else{
for(int i=1;i<10;i++){
if(temp%(i*10)==0 && temp/(i*10)==1){
return i;
}
}
}
}
int main(){
int no=100;
printf("%d",ten((no)));
return 0;
}
Think about what happens when the number is greater than 99. You will not be able to find a value of i b/w 1 and 9 such that the expression in the if is true. You will need a value of i > 10, but of course, then it wouldn't be the tens digit of the number.
Your method only works for a specific case, ie, when the number is b/w 1 and 10^2. Sure, you could write some more code to make it work for numbers b/w 1 and 10^3, but that would just be a pain in the ass. Even then, you'd have to write more code if the number is greater than that.
Try to think of a solution for the general case. To do that, two facts would be very useful:
Dividing using / only gives the integer part of the answer. Eg: 66/10 = 6
% This operator gives you the remainder. Eg: 59%10 = 9
1) In the else block of ten() you are returning a value only if some condition is met. If the condition does not satisfy you are not returning anything. In that case a garbage value may be printed.
2) To get the tenth digit, that is a lot of work. Just change the function body to -
int ten(int x) {
return (x % 100) /10;
}
The numbers upto 99 gets correct result because the condition satisfies. Lets take 99 as an example. After unit digit subtraction you got 90. When i becomes 9, the temp%(i*10) becomes 0 and temp/(i*10) becomes 1.
When number is 100, after unit digit subtraction the number remains same(i.e. 100). But for values of i from 1 to 9 temp/(i*10) never becomes 1 and the loop quits, resulting in the absurd behavior. You will get the same behavior for all the numbers that are greater than 99 using your code.
I have a problem in understanding the condition of my program, I can hardly explain it in a sentence so I will explain the whole point of program.
So for my homework I got to make a program that will ask user to enter number N which will represent the number of elements in array, then user enters elements of that array (assuming that user will enter correct number of elements) program then needs compare every number from that array with a number X with XOR (^) Operator.
The task is to find a minimum value for that X in which will the resulting array have elements in ascending order. It sounds a bit complicated but this is how it should work:
You enter a number N: For example lets use 4.
Then you enter 1D array of 4 elements : Lets use 4 2 3 1
Then program needs to use a number X (do while loop) to test every number from
this array with that number and if that number is >= to the previous one, it
should continue to check the next and next until it reaches the number N
If every element is sorted in ascending(equal counts as ascending) order it
should display that number.
So for our example 4 2 3 1 when you use XOR operation with every one of them
with the X=6 you get array that looks like this 2 4 5 7 which is in ascending
order.
To explain: 4 in binary is 100 ; X in binary is 110 if you use XOR on
those you get 010 which is 2, and do as follows for the rest ( program does
everything)
So I made the program,everything works great returning good values for every example that we have for reference, my only problem is that I don't know when to stop looking for that number X, or how should I know that minimum X for that array of numbers doesn't exist. In that case my program runs forever and don't return any value,so basically an infinity loop.
I need to use code that is simple so nothing too complicated because this is a course "Introduction to programming" and they won't accept anything that was made using complex algorithms or something like that.
EDIt: The program should display -1 if there are no X.
Here is the code :
#include <stdio.h>
int main() {
int matrix[100];
int n;
int i;
int index=1;
int x=0;
int start=0;
int end=0;
printf("Enter N: ");
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&matrix[i]);
}
index=1;
x=0;
do {
start=matrix[index]^x;
if((matrix[index+1]^x) >= start)
index=index+1;
else x++;
if(index==n){
printf("X=%d",x);
end=1;
break;
}
} while(end!=1);
return 0; }
I'm trying to write a recursive function in C to take the value of 3 to the power of another number. For example, if I enter 4, the program will return the value 81. And the following code is the answer for the question. But I can not clearly understand how the code can solve the problem. I mean that when 4 is passed to the function, the first 3 lines in the function body will be ignored, jump straight into the " // This line " . Then how is it from there will the program return the number 81. The function calls itself again with 3 passed? 3*three_power(3) ? I can not clearly understand that. Can someone explain? Sorry because it's a stupid question, I'm new to C.
#include <stdio.h>
int three_power(int power);
int main(){
int a=4;
int b=9;
printf("\n3 to the power of %d is %d", a, three_power(a));
printf("\n3 to the power of %d is %d", b, three_power(b));
return 0;
}
int three_power(int power){
if (power < 1){
return( 1 );
} else
return (3* three_power(power-1)); //This line
}
Yes, it takes the else branch on the first way through, which causes the recursive call for 4 - 1 which again takes the else branch, and so on down to the base case when power is 0 which just returns 1 (since 30 is 1).
The full chain is
3 * three_power(3) =
3 * (3 * three_power(2)) =
3 * (3 * (3 * three_power(1)) =
3 * (3 * (3 * (3 * three_power(0))) =
3 * (3 * (3 * (3 * (1)))) =
3 * 3 * 3 * 3 = 81
It's hard to visualize, but that's it.
You can of course single-step through this in a debugger to get a feeling for it, or just add a printf("power=%d\n", power); to the first line of three_power().
This is the essence of recursion.
In a mathematical sense, you can define the power of 3^n as 3 * 3^(n - 1), right? After all 3 to the anything is 3 multiplied times itself that number of times, right?
The recursion simply says that the answer to "What is 3 to the power?" Well it is 3 times three_power of power minus one. You need only handle the case when power is 0 and the returned value will be multiplied times 3 by the number of recursive calls made.
This is an excellent learning exercise, but you should prefer pow(3, power) because it is more efficient to calculate this way and you don't risk to exceed the maximum recursive call stack.
Consider writing the command flow showing each entry and exit for your example. Also the return on the else is a single line else. I will rewrite it showing the correct brackets.
1e. enter with value 4
2e. enter with value 3
3e. enter with value 2
4e. enter with value 1
5e. enter with value 0
5r. return 1
4r. return 3*5r = 3*1 = 3
3r. return 3*4r = 3*3 = 9
2r. retrun 3*3r = 3*9 = 27
1r. return 3*2r = 3*27 = 81
int three_power(int power)
{
if (power < 1)
{
return( 1 );
}
else
{
return (3* three_power(power-1)); //This line
}
}
Another way of putting it with a single return is
int three_power(int power)
{
int rtnval;
if (power < 1)
{
rtnval = 1;
}
else
{
rtnval = 3* three_power(power-1); //This line
}
return rtnval;
}
This is an example of recursion, which is similar to the mathematical concept of induction. For a given input, is invokes itself on a reduced input, then uses that result to produce the desired result.
A good way to understand how the function works is to start with the simplest case, verify that it works, then move on to the next simplest case, etc.
In this example, the simplest case is when power is 0. In that case, it immediately returns 1. So far so good.
Now consider what happens when power is 1. In this case, it returns 3 * power(0). In other words, it calls itself with a different input, then uses that result to produce a new result. We have already verified that power(0) returns 1. So in this case, it will return 3 * 1, which is just 3. Again, so far so good.
So what happens when power is 2? Well, it returns 3 * power(1). This results in multiple nested calls. We know that power(1) will return 3, so this case will return 9. Again, it's doing what we want.
More generally, when power is >= 1, it recursively calls itself to obtain the result for power - 1. This will in general result in a chain of calls which eventually return the desired result for power - 1. It then multiplies this by 3 and returns the result. This is 3 * (3 ** (power - 1)), which is just 3 ** power as desired.
You can confirm its correctness inductively. The basis case is when power is 0. This case is confirmed directly. Then, assuming it gives the correct result for power - 1, we can see that it will also give the correct result for power, from the recursive step. It will only fail if the result becomes large enough to overflow.
I would propose a more efficient recursion than f(n)=3*f(n-1).
It would be
// f(n) = 1 if n = 0
// f(n) = f(n/2)^2` if n is even
// f(n) = 3*f(n/2)^2 if n is odd
int power3(int n)
{
int m;
if (n == 0)
return 1;
else if (n % 2 == 0)
{
m = power3(n/2);
return m*m;
}
else
{
m = power3(n/2);
return 3*m*m;
}
}
This way the time complexity is reducing from O(n) to O(log(n)).
Getting time limit exceeded on submitting answer. I am also facing same problem with 2-3 more questions that I have submitted on spoj.com.
http://www.spoj.com/problems/PRIME1/
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)
Here is my code in C.
#include <stdio.h>
int main()
{
int t,i,k,count;
long long int j=0,m=0,n=0;
scanf("%d",&t);
for(i=1;i<=t;i++)
{
scanf("%lld%lld",&m,&n);
for(j=m;j<=n;j++)
{
count=0;
for(k=1;k<=j/2;k++)
{
if(j%k==0)
count++;
if(count>1)
break;
}
if(count==1)
printf("%lld\n",j);
}
printf("\n");
}
return 0;
}
Your algorithm is O((m-n)*n) which of course won't run within the allocated time limit. Let's go over your code:
count=0;
for(k=1;k<=j/2;k++)
{
if(j%k==0)
count++;
if(count>1)
break;
}
if(count==1)
printf("%lld\n",j);
Micro optimization: Why do you need a counter? You could get away with a bool.
Optimization: Why are you testing primes j/2? If j has a divisor greater than 1 than it's guaranteed that j has a divisor that's at most sqrt(j).
Micro Optimization: Don't consider even numbers at all, except for 2.
bool prime = j==2 || j%2==1 ;
for(k=2;prime && k*k<=j;k++)
{
if(j%k==0) prime = false;
}
}
if(prime) printf("%lld\n",j);
Now this is O((m-n)*sqrt(n)) which is a lot faster.
I suppose this won't make the limit. You could extend the second micro-optimization to skip numbers divisible by 3 very easy.
Optimization: If this is still not enough then you have to do a pseudo-primality test. One test that's very easy to implement in O(log(n)) is https://en.wikipedia.org/wiki/Fermat_primality_test. With this the complexity is down to O((m-n)*log(n)) which should be run in the available time limit.
I cannot understand how the code is giving output of the prime factors of input..and what is the use of temp variable in this code?another question is what is the purpose of i=1 in the code fragment?
#include<stdio.h>
int main()
{
int number,i,temp;
scanf("%d",&number);
if(number<0)
{
printf("%d = -1 x ",number); //just printing
number=number*-1; //multiplication by -1
}
else
{
printf("%d = ",number); //just printing
}
for(i=2;i*i<=number;i++)
{
if(number%i==0)
{
printf("%d x ",i);
number=number/i;
temp=i;
i=1;
}
}
printf("%d\n",number);
return 0;
}
sample input:100
sample output:100 = 2 x 2 x 5 x 5
sample input:20
sample output:20 = 2 x 2 x 5
As previously mentioned, temp is unused.
The way this prints the prime numbers is by trying over and over to divide the number by the smallest number possible. That is the purpose of i=1.
So take 175.
First, the loop is initialized at 2. It then increments i until 175 % i == 0. When this happens, it means that i is a factor of 175. So it prints i and divides 175 by i. This ensures you won't double-count the factor. Here, this will happen first for i == 5. So now, num = 175/5 = 35.
At this point, i is reset to 1. The first thing that happens at the end of the loop block is that i is incremented to 2. So now again, it looks for the smallest factor. Again, it finds 5.
If i was not set to 1, the program would keep going up and it would miss the fact that 5 is a factor of 175 twice.
Eventually, when i > number, the program knows that it has found all the factors. This is because factors have to be less than the number they are factors of.
Hope this helps.
temp isn't used. i=1 resets the checking for factors at 1 once a factor is found
Here in this code..
i = 1
resets i as you want the prime factors.. else if it let to increment you will get values like 4 and 6 also.. which would be wrong.
no use of
temp = i;
Here temp variable is not used at all. You may remove it from pgm.
i=1 is done, so that checking of remainder if(number%i==0) can be started from value 2 again.