I wrote this small program to divide two 8 bit numbers with decimals (4 bit before and after comma):
void main()
{
// All numbers are in the format xxxx,xxxx
unsigned char a = 0b00010000; // Dividend = 1,0
unsigned char b = 0b00100000; // Divisor = 2,0
unsigned char r = 0; // Result
// Align divisor to the left
while ((b & 0b10000000) == 0)
{
b = (b << 1) & 0b11111110;
}
// Calculate all 8 bits
for (unsigned char i = 0; i < 8; ++i)
{
if (a < b)
{
// Append 0 to the result
r = (r << 1) & 0b11111110;
}
else
{
// Append 1 to the result
r = (r << 1) | 1;
a = a - b;
}
b = b >> 1;
}
printBinary(r);
getchar();
}
But all my results are shift to the left one digit too much.
So my results are 2 times bigger than they should.
I am so dump, even if I try to calculate 1 / 2 per hand I am making the same mistake:
0001,0000 / 0010,0000 = 0001,0000
0001,0000 / 1000,0000
-1000,0000 -> 0
0001,0000 / 0100,0000
-0100,0000 -> 0
0001,0000 / 0010,0000
-0010,0000 -> 0
0001,0000 / 0001,0000
-0001,0000 -> 1
0000,0000 / 0000,1000
-0000,1000 -> 0
0000,0000 / 0000,0100
-0000,0100 -> 0
0000,0000 / 0000,0010
-0000,0010 -> 0
0000,0000 / 0000,0001
-0000,0001 -> 0
Whats my mistake?
Related
I have implemented the Dijkstra's algorithm as follows
#include <iostream>
#include <bits/stdc++.h>
#include<cstdio>
#define ll long long int
#define mod 1000000007
#define pi 3.141592653589793
#define f first
#define s second
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define vfor(e, a) for (vector<ll> :: iterator e = a.begin(); e != a.end(); e++)
#define vfind(a, e) find(a.begin(), a.end(), e)
#define forr(i, n) for (ll i = 0; i < n; i++)
#define rfor(i, n) for (ll i = n - 1; i >= 0; i--)
#define fors(i, b, e, steps) for(ll i = b; i < e; i += steps)
#define rfors(i, e, b, steps) for(ll i = e; i > b; i -= steps)
#define mp make_pair
using namespace std;
void up(pair<ll, ll> a[], ll n, ll i, ll indArray[]) {
ll ind = (i - 1) / 2;
while (ind >= 0 && a[ind].s > a[i].s) {
swap(a[ind], a[i]);
indArray[a[ind].f] = ind;
indArray[a[i].f] = i;
i = ind;
ind = (i - 1) / 2;
}
}
void down(pair<ll, ll> a[], ll n, ll i, ll indArray[]) {
ll left = 2 * i + 1;
ll right = 2 * i + 2;
ll m = a[i].s;
ll ind = i;
if (left < n && a[left].s < m) {
ind = left;
m = a[left].s;
}
if (right < n && a[right].s < m) {
ind = right;
}
if (ind != i) {
swap(a[i], a[ind]);
indArray[a[i].f] = i;
indArray[a[ind].f] = ind;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// cout << setprecision(10);
ll n, m;
cin >> n >> m;
vector<pair<ll, ll>> a[n];
forr(i, m) {
ll u, v, w;
cin >> u >> v >> w;
a[u].pb(mp(v, w));
a[v].pb(mp(u, w));
}
ll parent[n];
parent[0] = -1;
pair<ll, ll> dist[n];
forr(i, n) {
dist[i] = mp(i, INT_MAX);
}
dist[0].s = 0;
ll ind[n];
iota(ind, ind + n, 0);
ll ans[n];
ans[0] = 0;
bool visited[n];
fill(visited, visited + n, false);
ll size = n;
forr(i, n) {
ll u = dist[0].f;
visited[u] = true;
ll d1 = dist[0].s;
ans[u] = dist[0].s;
swap(dist[0], dist[size - 1]);
size--;
down(dist, size, 0, ind);
for (auto e : a[u]) {
if (visited[e.f]){
continue;
}
ll v = e.f;
ll j = ind[v];
if (dist[j].s > d1 + e.s) {
dist[j].s = d1 + e.s;
up(dist, size, j, ind);
parent[v] = u;
}
}
}
stack<ll> st;
forr(i, n) {
ll j = i;
while (j != -1) {
st.push(j);
j = parent[j];
}
while (!st.empty()) {
cout << st.top() << "->";
st.pop();
}
cout << " Path length is " << ans[i];
cout << '\n';
}
}
This implementation is correct and giving correct output.
As it can be seen every time I select the node with lowest key value(distance from source) and then I update the keys on all the adjacent nodes of the selected node. After updating the keys of the adjacent nodes I am calling the 'up' function as to maintain the min heap properties. But priority queue is present in the c++ stl. How can I use them to avoid the functions up and down.
The thing is I need to be able to find the index of the node-key pair in the mean heap whose key needs to be updated. Here in this code I have used a seperate ind array which is updated every time the min heap is updated.
But how to make use of c++ stl
Like you implied, we cannot random-access efficiently with std::priority_queue. For this case I would suggest that you use std::set. It is not actually a heap but a balanced binary search tree. However it works the desired way you wanted. find, insert and erase methods are all O(log n) so you can insert/erase/update a value with desired time since update can be done with erase-then-insert. And accessing minimum is O(1).
You may refer to this reference implementation like the exact way I mentioned. With your adjacency list, the time complexity is O(E log V) where E is number of edges, V is number of vertices.
And please note that
With default comparator, std::set::begin() method returns the min element if non-empty
In this code, it puts the distance as first and index as second. By doing so, the set elements are sorted with distance in ascending order
% I did not look into the implementation of up and down of your code in detail.
You may not understand what I wrote clearly because English is not my first language.
Anyway, here is what I wrote.
public class Exercises7point11 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[][] binaryNumber = {{0,0,0},{0,0,0},{0,0,0}};
System.out.print("Enter a number between 0 and 511: ");
int decimalNumber = input.nextInt();
int subtractNumber = 256, number = decimalNumber;
for (int row = 0 ; row < 3; row++){
for (int column = 0 ; column < 3; column++) {
if(number >= subtractNumber) {
binaryNumber[row][column] = 1;
number = number - subtractNumber;
}
else {
subtractNumber = subtractNumber / 2;
binaryNumber[row][column] = 0;
}
}
}
// print
for (int row = 0; row < binaryNumber.length; row++){
for (int column = 0; column < binaryNumber[row].length; column++){
if (binaryNumber[row][column] == 1)
System.out.print("T ");
else if (binaryNumber[row][column] == 0)
System.out.print("H ");
if (column == 2)
System.out.print("\n");
}
}
}
Here is the details. Nine coins are placed in a 3-by-3 matrix with some face up and some face down. You can represent the state of the coins using a 3-by-3 matrix with values 0 (heads) and 1 (tails).
Such as,
1 0 0
0 1 0
1 1 0.
There are a total of 512 possibilities, so I can use decimal numbers 0, 1, 2, 3,..., 511 to represent all states of the matrix. Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.
My problem is "subtractNumber = subtractNumber / 2; binaryNumber[row][column] = 0;" in the 18 and 19 lines. Even though 'number is greater than or equal to subtractNumber, 18 and 19 lines are read.
I don't know how I can fix it.
Thank you so much!!
The output is a 3x3 matrix, but that doesn't mean you need to use a 2d array.
Here's a simpler approach. We're turning the user's input into a binary string using the toBinaryString method, then translating the binary string into H/T.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 0 and 511: ");
int input = sc.nextInt();
// Turn input to binary string
String binary = Integer.toBinaryString(input);
// Add enough zeros in front so that the string has 9 characters
binary = binary.format("%09d", Integer.parseInt(binary));
// Iterate through binary string one char at a time
for (int i = 1; i < 10; i++) {
if ('0' == binary.charAt(i - 1)) {
System.out.print("H ");
} else {
System.out.print("T ");
}
// New line after 3 letters
if (i % 3 == 0) {
System.out.println();
}
}
}
Example output
12 in binary is 000001100
Enter a number between 0 and 511: 12
H H H
H H T
T H H
I am trying to implement Miller-Rabin for the first time. My code is giving correct answer for all the testcases, i tried but still on SPOJ it is giving wrong answer.
Problem Statement: I am supposed to print "YES" if entered number is prime otherwise "NO"
Please help:
Problem Link: http://www.spoj.com/problems/PON/
CODE:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define LL long long
LL expo(LL a,LL b,LL c)
{
LL x=1,y=a;
if(b==0)
return 1;
while(b)
{
if(b%2==1)
x=(x*y)%c;
y=(y*y)%c;
b=b/2;
}
return x;
}
int main()
{
LL t,s,x,a,n,prime,temp;
scanf("%lld",&t);
srand(time(NULL));
while(t--)
{
scanf("%lld",&n);
if(n<2)
puts("NO");
else if(n==2)
puts("YES");
else if(n%2==0)
puts("NO");
else
{
s=n-1;
prime=1;
while(s%2==0)
s=s/2;
for(int i=0;i<20;i++)
{
a=rand()%(n-1)+1;
x=expo(a,s,n);
temp=s;
while((temp!=n-1)&&(x!=1)&&(x!=n-1))
{
x=(x*x)%n;
temp*=2;
}
if((x!=n-1)&&(temp%2==0))
{
prime=0;
break;
}
}
if(prime==0)
puts("NO");
else
puts("YES");
}
}
return 0;
}
Keep in mind that puts appends a newline character '\n' to the string that you're giving. You can try with printf instead.
I think your calculation of s and d is incorrect:
function isStrongPseudoprime(n, a)
d := n - 1; s := 0
while d % 2 == 0
d := d / 2; s := s + 1
t := powerMod(a, d, n)
if t == 1 return ProbablyPrime
while s > 0
if t == n - 1 return ProbablyPrime
t := (t * t) % n
s := s - 1
return Composite
I discuss the Miller-Rabin method in an essay at my blog.
You are getting wrong answer because of integer overflow as you are multiplying 2 long number which can't be holded in a single long long type.
Here is a solution in python to overcome the issue
import random
_mrpt_num_trials = 25 # number of bases to test
def is_probable_prime(n):
assert n >= 2
# special case 2
if n == 2:
return True
# ensure n is odd
if n % 2 == 0:
return False
# write n-1 as 2**s * d
# repeatedly try to divide n-1 by 2
s = 0
d = n - 1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
assert(2 ** s * d == n - 1)
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True
for _ in range(_mrpt_num_trials):
a = random.randrange(2, n)
if try_composite(a):
return False
return True
for i in range(int(input())):
a = int(input())
if is_probable_prime(a):
print("YES")
else:
print("NO")
For the purpose of the exercise, I have to implement the exponential function with the most basic arithmetic operations. I came up with this, where x is the base and y the exponent:
function expAetB() {
product=1;
for (i=0; i<y; i++)
{
product=product*x;
}
return product;
};
However, there are more basic operations than product=product*x;. I should somehow be able to insert instead another for loop which multiply and pass the result, but I can't find a way to do it without falling into an infinite loop.
In the same way that exponentiation is repeated multiplication, so multiplication is simply repeated addition.
Simply create another function mulAetB which does that for you, and watch out for things like negative inputs.
You could go even one more level and define adding in terms of increment and decrement, but that may be overkill.
See, for example, the following program which uses the overkill method of addition:
#include <stdio.h>
static unsigned int add (unsigned int a, unsigned int b) {
unsigned int result = a;
while (b-- != 0) result++;
return result;
}
static unsigned int mul (unsigned int a, unsigned int b) {
unsigned int result = 0;
while (b-- != 0) result = add (result, a);
return result;
}
static unsigned int pwr (unsigned int a, unsigned int b) {
unsigned int result = 1;
while (b-- != 0) result = mul (result, a);
return result;
}
int main (void) {
int test[] = {0,5, 1,9, 2,4, 3,5, 7,2, -1}, *ip = test;
while (*ip != -1) {
printf ("%d + %d = %3d\n" , *ip, *(ip+1), add (*ip, *(ip+1)));
printf ("%d x %d = %3d\n" , *ip, *(ip+1), mul (*ip, *(ip+1)));
printf ("%d ^ %d = %3d\n\n", *ip, *(ip+1), pwr (*ip, *(ip+1)));
ip += 2;
}
return 0;
}
The output of this program shows that the calculations are correct:
0 + 5 = 5
0 x 5 = 0
0 ^ 5 = 0
1 + 9 = 10
1 x 9 = 9
1 ^ 9 = 1
2 + 4 = 6
2 x 4 = 8
2 ^ 4 = 16
3 + 5 = 8
3 x 5 = 15
3 ^ 5 = 243
7 + 2 = 9
7 x 2 = 14
7 ^ 2 = 49
If you really must have it in a single function, it's a simple matter of refactoring the function call to be inline:
static unsigned int pwr (unsigned int a, unsigned int b) {
unsigned int xres, xa, result = 1;
// Catch common cases, simplifies rest of function (a>1, b>0)
if (b == 0) return 1;
if (a == 0) return 0;
if (a == 1) return 1;
// Do power as repeated multiplication.
result = a;
while (--b != 0) {
// Do multiplication as repeated addition.
xres = result;
xa = a;
while (--xa != 0)
result = result + xres;
}
return result;
}
I wanted to ask about , how can I use numbers with more than 32 digits in this code , the code is supposed to multiply two binary numbers with more than 32 digits , and even long wont work , and I dont know how should I use BigInteger in this code ! can anyone help , thanks
public static void main(String [] args)
{
long a , b ;
Scanner scanner = new Scanner (System.in);
a = scanner.nextLong();
b = scanner.nextLong() ;
long sumA = 0 ;
long sumB = 0 ;
double i = 0;
while ( a != 0 || b != 0)
{
sumA += (a % 10) * Math.pow( 2.0 , i ) ;
sumB += (b % 10) * Math.pow( 2.0 , i ) ;
a /= 10 ;
b /= 10 ;
i++ ;
}
a = sumA ;
b = sumB ;
long c = a * b ;
long temp = 0 ;
for (int k = 0 ; c!=0 ; k++)
{
temp +=( Math.pow(10.0, k) * (c % 2) );
c /= 2 ;
}
System.out.println(temp) ;
}
You want http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html.