How to find number of perfect squares in the given range? - c

It gives an error as terminated due to timeout for large input of t.
To find the number of perfect squares in the given range
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
double s,e,i;
int t;
scanf("%d",&t);
for (;t>0;t--)
{
int cnt=0;
scanf("%lf%lf",&s,&e);
for (i=s;i<=e;i++)
{
if (sqrt(i)==ceil(sqrt(i)))
cnt++;
}
printf("%d\n",cnt);
}
return 0;
}

There is a trick.
Find the square root of lower and upper bound
take their integral part and then
subtract the integral part of lower bound from upper bound.
You also need to check if lower bound is a perfect square or not. If it is then add 1 to the difference.
For example: Number of perfect squares between 1 and 100 is 10 - 1 = 9. Since 1 is also a perfect square therefore add 1 and hence result will be 10.
int result = (int)sqrt(upper_bound) - (int)sqrt(lower_bound);
if(lower_bound == (int)sqrt(lower_bound)*(int)sqrt(lower_bound))
result += 1;
Note that I considered upper and lower bound inclusive.

Method 2 (Efficient) We can simply take square root of a and square root of b and to count the perfect squares between them using
floor(sqrt(b)) - ceil(sqrt(a)) + 1
We take floor of sqrt(b) because we need to consider
numbers before b
We take ceil of sqrt(a) because we need to consider
numbers after a
For example, let b = 24, a = 8. floor(sqrt(b)) = 4
ceil(sqrt(a)) = 3 And number of squares is 4 - 3 + 1 = 2 The two numbers are 9 and 16

Related

Variable is exceeding specified limit in for loop

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.

Greatest product of consecutive digits

I need to find the greatest product of 10 consecutive digits in the 150-digit number in C but i cant see whats wrong.
I used nr[] to store the 10 consecutive numbers and nto store the biggest 10 number multiplie.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int array[150]={7,3,1,6,7,1,7,6,5,3,1,3,3,0,6,2,4,9,1,9,2,2,5,1,1,9,6,7,4,4,2,6,5,7,4,7,4,2,3,5,5,3,4,9,1,9,4,9,3,4,9,6,9,8,3,5,2,0,3,1,2,7,7,4,5,0,6,3,2,6,2,3,9,5,7,8,3,1,8,0,1,6,9,8,4,8,0,1,8,6,9,4,7,8,8,5,1,8,4,3,8,5,8,6,1,5,6,0,7,8,9,1,1,2,9,4,9,4,9,5,4,5,9,5,0,1,7,3,7,9,5,8,3,3,1,9,5,2,8,5,3,2,0,8,8,0,5,5,1,1};
int i,l,j,nr[10];
long int n=1,k;
for(i=0;i<140;i++){
k=1;
for(j=i;j<i+10;j++){
k=k*array[j];
}
if(n<k){
for(l=0;l<10;l++){
nr[l]=array[i+l];
}
n=k;
}
for(i=0;i<=9;i++){
printf("%d ",nr[i]);
}
return 0;
}
}
tryfor(i=1;i<=150;i++);
because you need 150-digit number
The biggest problem you have is that you have a return inside your outer for loop. That means you'll be exitting from your loop after you've looked at the first batch of 10 numbers.
You also have a problem in that you're printing your nr array inside your outer loop, so it will print a lot of stuff. You probably want it outside, just before your return.
Fixing those gives a string of:
9 4 9 4 9 5 4 5 9 5
I haven't checked, but there's a lot of 9's in there and nothing smaller than 4 so can easily imagine it's the largest string once multiplied.

Displaying primes from 2-10,000 in C

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.

Generating unique random numbers except from a specific one in C [duplicate]

This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 9 years ago.
I was wondering, how can I generate unique random numbers except from a specific one. For example, if I want to generate numbers in range 1 to 10 except from 3, the output should be something like this:
7 6 1 2 4 9 5 8 10
Shuffle the numbers 1 - 10 and remove 3.
It doesn't matter if you remove the 3 before or after shuffling.
Alternatively, shuffle the numbers 1 - 9 and relabel 3 as 10...
For shuffling without bias you can use for example the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Generate random number in the range 1..9 and add one if the number is greater than or equal to 3.
Generate a number. Check its value, if the number is 3 generate another one. If it isn't 3 then use it.
EDIT: Thinking before coffee is a terrible plan. If you want to get every number in the range in a random order then I agree with the others talking about shuffling lists. If however you want some random subset of the range I would store a list of forbidden values. Shuffling and only taking the first n numbers would also be suitable if the range isn't very large (e.g. not something like 0<x<INT_MAX).
Every time you generate a number check if the generated number is on the forbidden list and if it is, generate another number. Every time you generate a valid number you add it to the list to ensure generated numbers are unique. The list should also be initialised with your unwanted numbers (3 in the example given).
You may try like this:-
unsigned int
randomnumber(unsigned int min, unsigned int max)
{
double scaled = (double)rand()/RAND_MAX;
return (max - min +1)*scaled + min;
}
then later you can do this:-
x = randomnumber(1,10);
if (x==3)
{ x = x+1;}
or
if (x!=3)
{ printf("%d",x)}
This is my answer - returns random value in [min, max), except "except".
int myrand(int min, int max, int except) {
int rc;
do {
rc = min + rand() % (max - min);
} while(rc == except);
return rc;
}
This code will generate unique random numbers from minimum to maximum of a given range.
#include<stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int max_range, min_range, i = 0, rand_num;
srand((unsigned)time(NULL));
printf("Enter your maximum of range: ");
scanf("%d", &max_range);
printf("Enter your minimum of range: ");
scanf("%d", &min_range);
bool digit_seen[max_range + 1]; // VLAs For C99 only
for (int i = min_range; i <= max_range; i++)
digit_seen[i] = false;
for (;;)
{
rand_num = rand() % max_range + min_range;
if(rand_num !=3)
if(!digit_seen[rand_num])
{
printf("%d ", rand_num);
digit_seen[rand_num] = true;
i++;
}
if( i == (max_range - 1) )
exit(0);
}
return 0;
}

Populate a 2D Array by a rule

How do I populate an array like this:
1 2 3 4
2 3 4 3
3 4 3 2
4 3 2 1
I need to find out a formula that determines the pattern of populating this array.
#include <stdio.h>
#define N 4
int main()
{
int i,j,arr[N][N];
int a=1;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
{
arr[j][i]=i+j+1;
}
for(i=0; i < N; i++)
for(j=0;j<N;j++)
printf("%2i ",arr[j][i]);
printf("\n");
return 0;
}
It prints out similarly to the desired array except that I need "3" at the end of the second row, and after that point, it goes reversed. Please, explain me how to do that.
Try this:
arr[j][i]=N-abs(i+j-(N-1));
abs() can be used any time you need a numerical sequence which is mirrored around some value. You just need to subtract a constant such that the value you want to mirror around is zero, take the absolute, and then re-adjust the output.
In your case (with N = 4) the (i+j) summation produces: 0,1,2,3,4,5,6. The middle value is N-1, as the largest value is 2 * (N-1).
Subtracting N-1 (3) gives: -3,-2,-1,0,1,2,3.
The abs() gives: 3,2,1,0,1,2,3.
If we subtract that from N (4) we get the desired 1,2,3,4,3,2,1 sequence.
arr[j][i]=(j * 3 + j/ 3 + b) % N + 1;

Resources