I am a beginner and I am learning functions. Following is the code I have written to find if the given number is a prime. But when ever I execute it, I get the dialogue box saying "project.exe has stopped working". I am using dev c++ . any problem with my code?
#include<stdio.h>
int prime (int i);
int main()
{
int a,b;
scanf("%d",&a);
b=prime(a);
if (b==1)
printf("prime");
else
printf("not prime");
return 0;
}
int prime (int i)
{
int j=0;
for (j=0;j<=i;j++)
{
if (i%j==0)
break;
}
if (j==i)
return 1;
else
return 0;
}
Change this code block of your prime function:
int j=0;
for (j=0;j<=i;j++)
{
if (i%j==0)
break;
}
to:
int j;
for (j=2;j<=i;j++)
{
if (i%j==0)
break;
}
When you are trying to find the mod it actually tries to find it by division operation. You cannot divide a number by zero, as j is initially zero, you program is crashing.
It should start from 2, not from 0. 0 causes division by zero and that's cause why your program stops. Correct is:
int j;
for (j=2;j<i;j++)
{
if (i%j==0)
break;
}
if (j==i)
return 1;
else
return 0;
// or simply return j == i;
You need to return a value that is not one. Something like this ...
int prime (int i) {
int j;
if (i <=3) return 1;
for (j=2;j<i/2;j++)
if (i%j==0) return j;
return 1;
}
Checking if the number i is greater than 3 is also important.
Related
I am trying to implement a merge sort algorithm in C. In the recursive array split function, my base case is occurring infinitely, despite the return statement, and the merge function is never called. Here is my code:
#include <stdio.h>
const int MAX = 1000;
int getArray(int unsorted[MAX], int upperBound)
{
int i;
for(i = 0; i <= upperBound; ++i)
{
printf("Now enter integer number %d: ", i + 1);
scanf("%d", &unsorted[i]);
while((getchar()) != '\n');
}
printf("\n");
return 0;
}
int merge(int unsorted[MAX], int sorted[1000], int lowerLeft, int lowerRight)
{
if(lowerLeft == lowerRight)
return 0;
int j = lowerRight;
for(int i = lowerLeft; i < lowerRight; ++i)
{
if(unsorted[i] <= unsorted[j])
{
sorted[i] = unsorted[i];
++j;
}
else
{
sorted[i] = unsorted[j];
++j;
}
}
return 1;
}
int split(int unsorted[MAX], int sorted[1000], int lowerBound, int upperBound)
{
printf("%d is the lBound and %d is the uBound\n", lowerBound, upperBound);
if(lowerBound == upperBound)
{
printf("\nBase case triggered.");
getchar();
return 0;
}
int middle = upperBound/2;
split(unsorted, sorted, 0, middle);
split(unsorted, sorted, middle + 1, upperBound);
merge(unsorted, sorted, lowerBound, middle);
return 1;
}
int main()
{
int unsorted[MAX];
int sorted[MAX];
int lowerBound = 0;
int upperBound;
printf("First enter the number of integers you wish to sort: ");
scanf("%d", &upperBound);
while((getchar()) != '\n');
printf("\n");
upperBound = upperBound - 1;
getArray(unsorted, upperBound);
split(unsorted, sorted, lowerBound, upperBound);
printf("\n");
for(int c = 0; c < upperBound; ++c)
{
printf("%d, ", sorted[c]);
}
return 0;
}
Why won't the merge function be called after reaching the base case? Sorry if I didn't phrase the question conveniently, hoping someone can help me out here, thanks.
Your base case is being triggered because that's how recursive algorithms work. You keep calling split() over and over again with a lower and lower gap between lowerBound and upperBound, so eventually your base case gets triggered. And that should be a good thing, since triggering the base case lets you know that your input "arrays" (singletons) are sorted and can be merged.
The reason it gets triggered "immediately" is that it must: split() gets called continually until the base case is met, so the first print statement you'll see is the base case one.
The code given below passes two test cases and sieve of eratosthenes passes 1 test case. How can this problem be solved.
I have already tried miller rabin and sieve eratosthenes primality test.
None is passing all the test cases because of time restriction. Is there any possible way faster than these?
The below code is passing two of the 5 test cases. Can it be made any shorter in terms of time complexity?
#include<stdio.h>
#include<math.h>
int isPrime(int n)
{
int i;
int x=(int)(sqrt(n));
if(n==2)
return 1;
else if(n%2==0)
return 0;
else
{
for(i=3;i<=x;i+=2)
{
if(n%i==0)
{
return 0;
}
}
}
return 1;
}
int counting(int *a,int n)
{
int i,c=0;
for(i=0;i<n;i++)
{
if(isPrime(a[i]))
c++;
}
return c;
}
void main()
{
int cases,n,a[100000],i,j,count;
scanf("%d",&cases);
for(i=0;i<cases;i++)
{
scanf("%d",&n);
for(j=0;j<n;j++)
scanf("%d",&a[j]);
count=counting(a,n);
printf("%d\n",count);
}
}
Maybe you should try this algorithm, i got from this site. It seems to be more time-efficient:
#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for(i = 2; i <= n/2; ++i)
{
// condition for nonprime number
if(n%i == 0)
{
flag = 1;
break;
}
}
if (n == 1)
{
printf("1 is neither a prime nor a composite number.");
}
else
{
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}
A person has to cross a road and with each step he either gains some energy or loses some (this info is provided as an array) . Find out the min amount of energy he should start with so that at any level his energy is not less than 1.
But the below program always prints "Error" not the number.
#include<stdio.h>
#include<limits.h>
int main(){
int a[]={10,20,20};
int n = sizeof(a)/sizeof(a[0]);
int ans = calldistance(a,n);
if(ans==-1)
printf("error");
else
printf("%d",ans);
return 0;
}
int calldistance(int a[],int n){
int i,min=INT_MAX;
for(i=0;i<n;i++){
min+=a[i];
if(min<1) return -1;
else continue;
}
return min;
}
You always return -1 because you call it quits if the array is one where the value isn't trivial.
You need to keep track of partial sums of the array. In particular you need to know when the partial sum is at its lowest negative value (or zero). The absolute value of this + 1 is your answer.
If the sum is never bellow 1, then your answer is just 1.
int calldistance(const int a[], const int n) {
int min_partial_sum = 0;
int partial_sum = 0;
for(int i = 0; i < n; ++i) {
partial_sum += a[i];
if(min_partial_sum > partial_sum)
min_partial_sum = partial_sum;
}
if(min_partial_sum < 0)
return -min_partial_sum + 1;
return 1;
}
int calldistance(int a[],int n){
int i,min=INT_MAX;
for(i=0;i<n;i++){
min+=a[i];
if(min<1) return -1;
else continue;
}
return min;
}
In the above function you are initializing min=INT_MAX and if you add even 1, it will return a negative number. That's the why you are always getting error as answer.
code is used to scan integers into an array the loop is to stop scanning when 0 is input.
after values are scanned in the highest and lowest values inside the array are to be found
after finding high and low , print the values between the the array indexs of high and low
so if input 5,2,8,7,6,12,6,4,5
output should be 2,7,6,12
my program fails after it scans in the input values and 0 is input to end the loop
#include <stdio.h>
int main(){
int high=4;
int low,i;
int array[25];
int count=0;
printf("Please input numbers for array:");
for(i=0;array[i]!=0;i+=1){
scanf("%d",&array[i]);
count+=1;
}
for(i=0;i<count;i+=1){
if(array[i]>array[high]){
high=i;
}
}
low=high;
for(i=0;i<count;i+=1){
if(array[i]<array[low]){
low=i;
}
}
for(i=low;low<=high;i+=1){
printf("%d,",array[i]);
}
}
The for loop checks the condition before each iteration, so in
array[i]!=0
you are checking uninitalized value, before reading in array[i]. If it doesn't happen to find a zero hanging around somewhere in memory, this can go on reading more than 25 values, it can even go on and on till you get a stack overflow.
Also, in the other for loops, you probably meant
i < count
The condition
low<high
is just really not appropriate.
Here is a version that should work more like expected:
#include <stdio.h>
int main(){
int high;
int low,i;
int array[25];
int count=0;
int start;
int end;
printf("Please input numbers for array:");
for (i = 0; scanf("%d", &array[i]), array[i] != 0; i += 1) {
count+=1;
if (i >= 25) {
printf("Unable to handle more than 25 input values\n");
break;
}
}
high = 0;
for (i = 1; i < count; i += 1) {
if (array[i] > array[high]) {
high = i;
}
}
low = 0;
for (i = 1; i < count; i += 1) {
if (array[i] < array[low]) {
low=i;
}
}
if (low < high) {
start = low;
end = high;
}
else {
start = high;
end = low;
}
for (i = start; i <= end; i += 1) {
printf("%d", array[i]);
if (i != end) {
printf(",");
}
else {
printf("\n");
}
}
}
#include <stdio.h>
int main(){
int low, high, array[25];
int i, count=0;
printf("Please input numbers for array:");
for(i=0;i<25;++i){
int data;
scanf("%d", &data);
if(data==0)
break;
array[count++]=data;
}
low = high = 0;
for(i=1;i<count;++i){
if(array[i]<array[low])
low=i;
if(array[i]>array[high])
high=i;
}
for(i=low;i <= high;i++){
printf("%d,", array[i]);
}
}
I've got your code working after some minor changes
#include <stdio.h>
int main()
{
int high=0; // high value assumed to be zero for ease of understanding
int low=0,i; // low value assumed to be zero for ease of understanding
int array[25];
int count=0;
printf("Please input numbers for array:");
for(i=0;;i+=1){
scanf("%d",&array[i]);
count+=1;
if(array[i]==0) // Whenever is zero is read the loop is immediately exited, otherwise looping is continued
break;
}
count--; // decrement one count (count of zero)
for(i=1;i<count;i+=1){
if(array[i]>array[high]){
high=i;
}
}
for(i=1;i<count;i+=1){
if(array[i]<array[low]){
low=i;
}
}
for(i=low;i<=high;i+=1){ //printing from low value upto high value
printf("%d,",array[i]);
}
}
I'm new to C, and I'm getting a segmentation fault that I can't understand. I have the following program, which attempts to calculates the number of factors of a strictly positive number:
#include <stdio.h>
#include <math.h>
int numberOfFactors (int number, int factor) {
if (number % factor == 0) {
number = number/factor;
return numberOfFactors(number, factor) + 1;
} else {
return 0;
}
}
int check (int x) {
if (x>0) {
return 1;
} else {
return 0;
}
}
int main(void) {
int number;
printf("Please enter a positive integer n such that n >= 1: ");
scanf("%d", &number);
if (check(number)){
int i;
for (i=1; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
}
return 0;
}
The segmentation fault occurs immediately after entering an integer and ENTER after these lines in main():
printf("Please enter a positive integer n such that n >= 1: ");
scanf("%d", &number);
What in these lines is causing the segmentation fault, and what can I do to avoid it?
Your recursion doesn't stop if you try to divide out factor one.
Just let factor never be 1:
for (i=2; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
I should say WHY it segfaults: It's because every function call pushes the current program counter (the position in your program where you currently stand) and function arguments on the stack (aka call stack), where the stack is a relatively small memory block used for, well, function calling and local variables.
So if you are pushing your stack too hard, it will fall over. End of game, aka segfault ;)
You probably have a problem with this recursion:
int numberOfFactors (int number, int factor) {
if (number % factor == 0) {
number = number/factor;
return numberOfFactors(number, factor) + 1;
} else {
return 0;
}
}
Change your numberOfFactors to something like:
int numberOfFactors (int number)
{
int i=1;
int ret=0;
for(;i<=number;i++) {
if (number%i == 0) {
ret++;
}
}
return ret;
}
And then, change this portion:
if (check(number)){
int i;
for (i=1; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
}
To something simpler like:
if (check(number)){
factors = numberOfFactors(number);
printf("%d^%d ", number, factors);
}