Comparing both function on If and Else - c

Got this question just now when I’m tried comparing my program to both of my classmates (2 of them), and the results is there results came early (about 2 sec). Note that I forget to use the clock() function.
On if/else condition, is using the ternary operator
(Condition) ? (True) : (False);
slower than using this?
if (condition) {
(function if True)
}else {
(function if False)
}

There is no difference in terms of speed. Use ternary conditional only if you want to type less.
See the following example:
void f1(int i) {
int val = (i > 10) ? i * 5 : i * 10;
}
void f2(int i) {
int val;
if(i > 10){
val = i * 5;
}else{
val = i * 10;
}
}
See the compiler generated assembly for both the functions here.
There is no difference.

Related

Understanding purpose of and difference between given recursive functions

Below are the two pieces of code. I could not understand how the pre-decrement operator in the first code functions. And I also could not understand how both of the codes differ in their functionality.
Code 1:
int foo (int val) {
int x = 0;
while (val > 0) {
x = x + foo(--val);
}
return val;
}
Code 2:
int bar (int val) {
int x = 0;
while (val > 0) {
x = x + bar(val - 1);
}
return val;
}
Consider the original code:
int foo(int val) {
int x = 0;
while (val > 0) {
x = x + foo(val--); // Post-decrement
}
return val;
}
When foo() calls itself recursively, the value passed to the recursive call is the same as the value passed to the current call, so the program will eventually exceed the stack limit and crash. It won't terminate normally.
Now consider the revised code:
int foo(int val) {
int x = 0;
while (val > 0) {
x = x + foo(--val); // Pre-decrement
}
return val;
}
Now the recursion is finite; if val is positive, then the recursive call is made with a smaller value, so the recursion stops. If val is negative, there is no recursion, of course.
However, since the code returns val, it will always return either 0 (for a non-negative input, because the loop counts down until val == 0) or what was provided (for a negative input; the loop body is never executed). The recursion keeps adding 0 to x, so x remains 0 too (but it's a 'set but unread' variable so it could be eliminated, and writing x += foo(val--); would be more idiomatic C). It would be accurate to say the revised code is equivalent to:
int foo(int val) { return (val < 0) ? val : 0; }
Even returning x doesn't fix all the problems. It returns 0 for non-negative inputs and 0 for negative inputs (but it doesn't crash):
int foo(int val) {
int x = 0;
while (val > 0) {
x += foo(--val); // Pre-decrement
}
return x;
}

Why Golang is faster than ANSI C and how can I optimize my solution?

I wrote benchmarks to check how fast if statements can be handled by Golang and ANSI C respectively. I was trying to keep the same schema overall solutions.
Solution in ANSI C is following;
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void bench(void (*f)(int));
void if_func_1(int i);
void if_func_2(int i);
void if_func_3(int i);
int main() {
bench(&if_func_1);
bench(&if_func_2);
bench(&if_func_3);
return 0;
}
void bench(void (*f)(int)) {
int i;
struct timespec start, end;
float delta_us;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for (i = 2147483647; -2147483648 != i; i--) {
(*f)(i);
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) * 0.001;
printf("%.3fms\n", delta_us * 0.001);
}
void if_func_1(int i) {
if (0 == i) {
return;
}
if (1 == i) {
return;
}
if (2 == i) {
return;
}
if (3 == i) {
return;
}
return;
}
void if_func_2(int i) {
if (0 == i) {
return;
} else if (1 == i) {
return;
} else if (2 == i) {
return;
} else if (3 == i) {
return;
}
return;
}
void if_func_3(int i) {
if (0 == i || 1 == i || 2 == i || 3 == i) {
return;
}
return;
}
The results were folowing:
~ time ./app.bin
20875.278ms
28766.584ms
16371.974ms
./app.bin 65.59s user 0.09s system 99% cpu 1:06.02 total
As I expected if_func_3 was the fastest one because it implements different logic.
In Golang my solutions is following:
package main
import (
"fmt"
"time"
)
func main() {
bench(if_func_1)
bench(if_func_2)
bench(if_func_3)
}
func bench(f func(int)) {
var i int = 0
start := time.Now();
for i = 2147483647; -2147483648 != i; i-- {
f(i)
}
elapsed := time.Since(start)
fmt.Println(elapsed)
}
func if_func_1(i int) {
if 0 == i {
return
}
if 1 == i {
return
}
if 2 == i {
return
}
if 3 == i {
return
}
return
}
func if_func_2(i int) {
if 0 == i {
return
} else if 1 == i {
return
} else if 2 == i {
return
} else if 3 == i {
return
}
return
}
func if_func_3(i int) {
if 0 == i || 1 == i || 2 == i || 3 == i {
return
}
return
}
I could use pointers here because they don't exist in Golang.
Resutls are quite confusing.
~> time go run app.go
11.595459054s
13.062146816s
14.504122183s
go run app.go 39.33s user 0.34s system 92% cpu 42.746 total
What causes such difference in these two solutions? How can I optimize ANSI C solution to perform better?
Enviroment specification
System MacOS
gcc version 10.0.0
go version 1.10.3
Compiled with -ansi --pedantic -Wall flags.
Summary
After adding -O and changing the trivial return to print some text. Total execution timings have changed.
For ANSI C
From: System 99% cpu 1:06.02 total
To: System 99% cpu 8.552 total
For Golang
From: system 98% cpu 43.634 total
To: system 92% cpu 42.746 total
All your tested functions are trivially equivalent to void no_op(int) {}. The large timing differences are just possible because you are compiling without optimizations, which makes your benchmark results dubious at best.
Proper benchmarking requires turning on optimizations (i.e. -O or higher for GCC and Clang), and taking care that the relevant parts are, however, not optimized out. It can appear to be a simple problem, but is often surprisingly hard in practice. I recommend using a benchmarking library such as google benchmark to make the problem a bit more manageable.
I see that you updated your question with compiler version and settings, which is a good thing. Performance-related questions tend to have either somewhat or highly implementation-dependent answers, so this information should always be included in this kind of question (for that matter, it never hurts for any question involving a test program). You should also add the version of and switches for Golang that you are using.

Determine if a number is a prime without using loops and mutations?

How can I determine is a number is a prime without using a loop? I'm a beginner student and so far I've only been taught functional C. All I am allowed to use is the most basic code like + -, if, ==,!,||....Also, no variable mutations are allowed, all variables must be constant.
Here is my code with mutation:
bool prime(const int i, int a) {
if (a > i/2){
return false;
}
if (i%a == 0){
return true;
}
else {
return prime(i, a+1);
}
}
# int a is a counter its given initial value is always 2
#prime (5,2) --> false
#prime (9,2) --> true
However, as the question requires, no mutation is allowed, and only one variable is consumed so it should look like
bool prime(const int i) {
...
}
I'm thinking of a recursive approach but I just can't quite figure it out.
Also efficiency is not a factor to be considered in this problem.
Any help will be appreciated, thanks!
With an auxiliary function it should be more or less easy, although terrible innefficient:
bool prime(const int i)
{
prime_aux(i, i-1);
}
bool prime_aux(const int i, const int d)
{
if (d == 1) return true;
if (i % d == 0) return false;
return prime_aux(i, d - 1);
}
There are some easy optimizations out there, but I omitted them because the code is prettier this way. Also some checks to the input parameters may be needed before proceeding.
Only way I can think of is:
bool prime(const int i)
{
assert(i >= 0);
return char_array_odd_primes_const[i / 8] & (1U << (i % 8)) ? true : false;
}
Where char_array_primes_const contains 231 bits which are set to 1 for prime numbers and 0 for non-prime.
More efficient would be:
bool prime(const int i)
{
assert(i >= 0);
if(2 == i) return true;
if(i % 2) return false;
return char_array_primes_const[i / 16] & (1U << ((i/2) % 8)) ? true : false;
}
check a given number prime or not without loop,Recursion,Auxiliary Function
import java.math.RoundingMode;
import java.util.Scanner;
public class PrimeNumberwithoutloop {
static void PrimeNumber(double num)
{
double n=num/6;
if(n<Math.round(n))
{ n=6*(Math.round(n))-1;
if(n==num)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
else
{ n=6*(Math.round(n))+1;
if(n==num)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to check prime or not");
double num=sc.nextDouble();
PrimeNumber(num);
}
}
Randomized Algorithms are known to exist for determining whether a no. is prime or not (and most probably they use only a single input(i do not have idead regarding all such algorithms), i.e., the number itself that is to be tested for its primality). These algorithms are proven to be accurate in maximum no. of situations, i.e., the probability with which they can give the correct result is very high(although not 100% like the usual deterministic algorithms that are written). If you want, you can use them.
Refer to the following link for more details:
http://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests
This is the best possible way without using loop.
const isPrimeNumber = (num) => {
if(num % 2 === 0 || num % 3 === 0 || num % 5 === 0 || num % 7 === 0 || (Math.sqrt(num) - Math.floor(Math.sqrt(num))) === 0 ) {
console.log(`${num} = is not a prime number`)
}
else {
console.log(`${num} = is a prime number`)
}
}
isPrimeNumber(161);
isPrimeNumber(25689);
isPrimeNumber(11);

Is there a difference between multiple if statements and else if?

If I write
int a = 1;
int b = 2;
if (a == b) {
//Do something
} else if (a > b) {
//Do something else
} else if (a < b) {
//Do something else
}
as opposed to:
if (a == b) {
//Do something
}
if (a > b) {
//Do something else
}
if (a < b) {
//Do something else
}
Is there a difference be it the way the compiler interprets the code or speed? I see no logical difference, but there surely must be a reason why an if else statement exists. It's just a single line break difference.
In the scenario above, they are the same, other than speed. If/else will be faster than a series of ifs, because else statements are skipped if the if condition is satisfied. In a series of ifs, on the other hand, each condition is evaluated separately.
In other scenarios, of course, the logic is not the same, and so replacing if/else with a series of ifs breaks the program. Example:
// this:
if(x <= 0) {
x = 1;
}
else { // only true if x started out > 0
x = 37;
}
// is different from this:
if(x <= 0) {
x = 1;
}
if(x > 0) { // always true in this version
x = 37;
}
In else-if statements, when a condition is met, all other else-ifs are skipped.
Whereas in multiple if statements, it has to go through all of them.
To be more precise, Lets suppose a=b.
Consider your first code block:
int a = 1;
int b = 1;
if (a == b)
{
//Do something
}
else if (a > b)
{
//Do something else
}
else if (a < b)
{
//Do something else
}
While executing, since a=b, it will skip all other conditions (a>b & a<b).
Checks if a=b.
Executes the code block.
All others are skipped.
Consider your second code block:
int a = 1;
int b = 1;
if (a == b)
{
//Do something
}
if (a > b)
{
//Do something else
}
if (a < b)
{
//Do something else
}
Even the first condition is met, all of them will be evaluated.
Checks if a=b.
Executes the code block.
Checks if a>b.
Checks if a<b.
In second type of code you wrote. Compiler will show out put for each true statement and will not skip any condition. Else command is use to make sure that one of two conditions are matched.
the time complexity of if-else statements is less as compared to multiple if statements. Therefore if-else steements are much advantageous

C: Function in an if statement

I want to do something like this:
if([FUNCTION] > 3){
//do stuff
}
where FUNCTION is a function that performs some action and returns the result as an int. For example, function can be defined as:
a + 1;
return a;
where a was a previously defined variable. Is there any way to do this in C? Many thanks!
First of all
a + 1;
is a statement with no effect, so I'm assuming you meant a = a + 1. Then yes, you can of course call a function from within an if statement.
int foo(int* a) {
*a = *a + 1;
return *a;
}
// later ...
int a = 7;
if (foo(&a) > 3) {
// do stuff
}
If a is not known in the scope of the if statement, you probably meant something like this:
int a = 7;
int foo() {
a = a + 1;
return a;
}
// later ...
if (foo() > 3) {
// do stuff
}
Since grammatically, C allows if ( expression ) and a function call on the left of a relational expression with > is an expression as well, the answer is yes, you can do this in the straightforward way,
if (some_function() > 3) {
/* Do stuff. */
}
What kind of C book is it that doesn't make this clear? I highly recommend Kernighan, Ritchie, The C Programming Language, 2nd Edition (update for ANSI/ISO C89).
#include<stdio.h>
int a=5;
int foo(int a)
{
a++;
return a;
}
int main()
{
if(foo(a) > 3) {
printf("%d\n",a);
// Do stuff
}
return 0;
}
It's simple.
EDIT :It's just a demo source code to show that if condition returns true.

Resources