Where is the code wrong? - c

I'm trying to solve this problem from the UVA Online Judge: http://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2456
The problem statement
A square number is an integer number whose square root is also an integer. For example 1, 4, 81 are
some square numbers. Given two numbers a and b you will have to find out how many square numbers
are there between a and b (inclusive).
The code I've attempted:
#include <stdio.h>
int main()
{
long long int num1, num2, count = 0;
int t, i;
while (1)
{
count = 0;
scanf("%lld%lld", &num1, &num2);
if (num1 == 0 && num2 == 0)
break;
for (; num1 * num1 <= num2; num1 ++)
count++;
printf("%lld\n", count);
}
return 0;
}
The Judge's Response
The Online submission process tells me that my code produces the wrong answer, but I'm not able to figure out why. Can anyone see the error in my code?

The first problem you have is that you misunderstand the problem statement.
You should not calculate the square of the numbers but the square root.
If the square root is an integer then and only then is it a square number.
Another way of getting the correct count is in fact calculating the square but not on the numbers from a to b but from the square root of a to square root of b.

Related

The full output is not being printed

im not getting an output for this program, please help
THE QUESTION:
Twin primes are consecutive odd numbers both of which are prime numbers. Write a program which inputs two positive integers A and B and outputs all twin primes in range A to B.
The code is:
#include <stdio.h>
int main(){
int num1,num2,temp,i,p1,p2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
p1=0;
p2=0;
printf("Twin prime numbers are:");
if(num1>num2){
temp=num1;
for(i=num2;i<temp;i=i+1){
int j;
for(j=2;j<i;j=j+1){
if(i%j!=0){
p1=1;
}
}
int k;
for(k=2;k<(i+2);k=k+1){
if((i+2)%k!=0){
p2=1;
}
}
if(p1==1 && p2==1 && (i+2)<=num2){
printf("\n%d and %d",i,i+2);
}
}
}
else{
temp=num2;
for(i=num1;i<temp;i=i+1){
int j;
for(j=2;j<i;j=j+1){
if(i%j==0){
p1=1;
}
}
int k;
for(k=2;k<(i+2);k=k+1){
if((i+2)%k==0){
p2=1;
}
}
if(p1==1 && p2==1 && (i+2)<=num1){
printf("\n%d and %d",i,i+2);
}
}
}
return 0;
}
OUTPUT:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Users\shaun\OneDrive\Desktop> cd "c:\Users\shaun\OneDrive\Desktop\c programming\programs\" ; if ($?) { gcc twin_primes.c -o twin_primes } ; if ($?) { .\twin_primes }
Enter 2 numbers: 8 19
Twin prime numbers are:
PS C:\Users\shaun\OneDrive\Desktop\c programming\programs>
if(p1==1 && p2==1 && (i+2)<=num2)
if(p1==1 && p2==1 && (i+2)<=num1)
You've mixed up with num2 & num1 in above 2 conditions.
If you use num1 instead of num2 and num2 instead of num1, you'll get the output.
Apart from this, there're several logical errors in code.
Logic to find prime number
Initializing variable p1 and p2 in proper place
To solve above 2 problems, I would recommend to learn more about finding prime numbers. I'll add some resources at below, please check those.
Another thing, you're basically writing same code twice. You could make it more simple by just swapping 2 given values when first one is larger than the second one.
Lastly, I'm giving a sample code here. It's one of the way you could follow to write simple but easily understandable solution for your problem.
Sample code:
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int num)
{
for(int i = 2; i * i <= num; i++)
{
if (num % i == 0) return false;
}
return true;
}
int main()
{
int num1,num2,temp,i,p1,p2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
p1=0;
p2=0;
printf("Twin prime numbers are:");
if (num1 > num2)
{
// swap the numbers. always keeping the first as the smaller one
int temp = num1;
num1 = num2;
num2 = temp;
}
if (num1 == 1) num1++; // ignoring 1
for(int i = num1; i <= num2 - 2; i++) // running the loop till num2 - 2, so we won't have to check whether i + 2 <= num2
{
if (isPrime(i) && isPrime(i+2))
{
printf("\n%d and %d",i,i+2);
}
}
return 0;
}
Please check below URLs to learn more about prime number and swapping values
C Program to Swap Two Numbers
C Program to Swap two Numbers GFG
Prime Numbers GFG
C Program to Check Whether a Number is Prime or Not
Which is the most efficient way to calculate prime numbers in C?
Quora

c program to calculate value of e^x, correct upto 10 decimal places

I am writing a program that calculates the value of e^x, according to the expansion formula.I need to print the answer so that it is correct upto 10 decimal places. I have tried to do it using, for, while and do while loop , however I cannot figure out where to terminate the loop , which condition to use to terminate the loop. i have written the code as follows:
#include<stdio.h>
#include<math.h>
int factorial(int x);
int main()
{
int x,n;
float sum,d_1;
printf("Enter the value of power :");
scanf("%d",&x);
n=1;sum=1;
while(sum <= %.10f)
{
d_1=pow(x,n)/factorial(n);
sum=sum+d_1;
n++;
}
printf("Answer is %f",sum);
return 0;
}
int factorial(int y)
{
int fact=1,i;
for(i=1;i<=y;i++)
{
fact=fact*i;
}
return(fact);
}
and i am getting the error message expected expression before %.
Please help.
You want to terminate the loop when the current term is smaller than some value. Also you want the loop to execute at least once, so a do-while loop is preferable:
n = -1;
do {
n++;
d_1 = pow(x, n) / factorial(n);
sum = sum + d_1;
} while (d_1 > epsilon);
As mentioned in the comments, there are other issues with the code when it comes to precision and overflow but that is a different story.

Using While-Loops to Find the Smallest Divisor of a Number

I've been studying C programming again with the usage of my "C How to Program" textbook. As an exercise within the text, I have been prompted to find the smallest divisor of a number supplied by a user. Just to clarify, just in case, a number is a divisor if the division results in a remainder of 0, and we are looking for a divisor greater than 1. To complete this, it instructs that I should use a while-loop. I have just begun using while-loops, so I understand the basic idea and function, but not exactly how to execute everything properly in this situation. Seeing this example will grant me a better understanding. I take it as that I am supposed to create some code that looks for a divisor, counting up until it finds one. Thank you for any help that you provide. It is greatly appreicated.
Best regards!
To find the smallest divisor, you need to check from 2 to n that which number's division results in a remainder of 0. The first number which division results in a remainder of 0 is the smallest one. See the implementation below:
int n, i;
scanf("%d", &n);
i = 2;
while(i <= n){
if(n % i == 0){
printf("The smallest number is %d\n", i);
break;
}
i++;
}
But u can do it more efficiently. you don't actually need to traverse till n. Traversing till square root of n is enough to find this. if you don't find the smallest number after traversing till the square root of n that's mean the smallest number is n itself. see the implementation below.
#include <stdio.h>
#include <math.h>
int main()
{
int n, i, sq;
scanf("%d", &n);
i = 2;
sq = sqrt(n);
while(i <= sq){
if(n % i == 0){
printf("The smallest number is %d\n", i);
break;
}
i++;
}
if(i > sq){
printf("The smallest number is %d\n", n);
}
}

Find the sum of digits of a number(in c)

I need to find the sum of the digits of a number. For example, the sum of the digits of the number 1123 is 1+1+2+3 =7
My idea:
1)User enters and integer
2)I calculate the number of digits in the number(in case above - 4 digits)
3)Than using for loop I divide users number by 10 to the power of 1,2...till the number of digits(not including the last one) and sum the numbers.
Here is my code:
int main (void)
{
int result,sum,n;
int div = 10,counter = 0,number;
printf("Enter the integer:");
scanf("%i",&number);
while(result >0){
result = number/div;
div *= 10;
++counter;
}
printf("The number consists of %i digits\n",counter);
sum = 0;
for(n=1;n<counter;++n){
sum += number/pow(10,n);
}
printf("%i",sum);
return 0;
}
the first part(while loop) separately works correct. But together with second part(for loop) it gives me incorrect result(0 digits from the while loop and the sum is also zero). Can you explain why does it happen?
How can I correct my solution?
P.S I know that exist more efficient solutions of my problem, but i want to use my own algorithm.
Several problems here:
When you first enter the while loop, result has not been initialized. Attempting to read an uninitialized variable is undefined behavior.
When you do the division, you aren't adding digits. You're adding the number divided by successive powers of 10. In the case of 1123, you're actually adding 112 + 11 + 1. You need to use modulus instead of division to get the digits.
You can do the adding and counting of digits in a single loop as follows:
sum = 0;
while(number > 0){
sum += number % 10;
number /= 10;
++counter;
}
printf("The number consists of %i digits\n",counter);
printf("%i",sum);
much simpler:
result = number;
sum = 0;
counter = 0;
while(result != 0){
sum += result % 10;
result /= 10;
++counter;
}
printf ("Counter:%d sum:%d\n", counter, sum);
First of all, for best debugging, use a number which has different digits, like 12345.
To do debugging, calculate and print the digit separately from accumulating it. That is, instead of sum += <... complex code ...>, do it like this:
int digit = ...
printf("Next digit is %i\n", digit);
sum += digit;
Also (you should discover this by debugging, but it's obvious enough to note directly), your algorithm for calculation of digits is wrong. Do something like this:
int div = 1;
for (...)
{
digit = number / div % 10;
div *= 10;
}
Note that I don't use pow here, because pow uses floating-point arithmetic, which has limited accuracy. If your int has 64 bits of precision (unlikely but possible), floating-point will calculate nonsense for large numbers (it has only 53 bits of precision).
There are many errors in the code, but overall the whole approach is wrong. Counting the digits is unnecessary.
A simpler way would be:
unsigned temp = number, sum = 0;
while (temp) {
sum += temp % 10;
temp /= 10;
}
Notice that you know when to stop looping because temp becomes 0 (temp as a condition is equivalent to temp != 0). You don't need to know the number of digits in advance.
If going with your code, this'll work:
for(n=1;n<=counter;++n){
sum += number%10;
number /= 10;
}
printf("%d",sum);
Simpler solution:
int c, n=0, sum=0;
printf("Enter number");
while((c=getchar())!='\n') { // IMPORTANT: '\n' in unix, '\r' in windows
if(c<'0' || c>'9') {
printf("Bad value");
break;
}
sum+=c-'0'; // c is the ASCII code of the digit, so you have to subtract an offset
n++;
}
printf("Number of digits: %d", n);
printf("Sum of digits: %d", sum;

How to Print Out the Square Root of A Negative Number with i Displayed in C

I am trying to figure out how to display the square root of a number if it happens to be negative (as it is entered by the user), and if so, display it correctly with the "i" displayed as well. When I do the normal sqrt function, the result is always something like -1.#IND. When I tried using the double complex variables, the positive numbers nor the negative numbers would come out clean.
Below is my code; the comments are what my goal is. The 4 num variables are entered by the user and can be any integer, positive or negative.
// Display the square root of each number. Remember that the user can enter negative numbers and
// will need to find the negative root with the "i" displayed.
printf("\nThe square root of %d is %.4f", num1, sqrt(num1));
printf("\nThe square root of %d is %.4f", num2, sqrt(num2));
printf("\nThe square root of %d is %.4f", num3, sqrt(num3));
printf("\nThe square root of %d is %.4f", num4, sqrt(num4));
If you're working with floating point you can use the built-in complex utilities, e.g.:
#include <complex.h>
#include <stdio.h>
int main(void)
{
double complex num = -4.0;
double complex s = csqrt(num);
printf("%.2f + %.2fi\n", creal(s), cimag(s));
}
You can use:
if ( num1 < 0 )
{
printf("\nThe square root of %d is %.4fi", num1, sqrt(-num1));
}
else
{
printf("\nThe square root of %d is %.4f", num1, sqrt(num1));
}
Pseudocode:
string root(int num) {
return "" + sqrt(abs(num)) + (num < 0) ? "i":"";
}
Alternatively:
printf("\nThe square root of %d is %.4f%s", num1, sqrt(abs(num1)), (num1 < 0) ? "i":"");

Resources